- 1 year ago
Use / for path on Windows, and have stdlib functions use it as well (glob, os.path, etc.)
To use forward slashes ("/") as path separators in Windows and have standard library functions like glob
, os.path
, etc. recognize and work with them, you can use the Pathlib
module introduced in Python 3.4.
Here's an example of how you can use Pathlib
to work with forward slashes in paths on Windows:
pythonfrom pathlib import Path
# Use forward slashes in the path
path = Path("C:/path/to/file.txt")
# Use Pathlib functions to work with the path
print(path.exists())
print(path.is_file())
print(path.parent)
# Use glob to search for files
for file_path in Path("C:/path/to/folder").glob("*.txt"):
print(file_path)
In the example above, we import the Path
class from pathlib
and create a Path
object using forward slashes in the path string (C:/path/to/file.txt
). We can then use various Path
methods like exists()
, is_file()
, and parent
to work with the path.
Additionally, we can use Path
with the glob
function to search for files using a pattern. The pattern can contain forward slashes as path separators, and glob
will correctly match the files.
By using Pathlib
, you can work with paths using forward slashes on Windows while still leveraging the functionalities provided by the standard library functions like glob
, os.path
, etc.