'Issue with slashes (\) in listdir
I have been having issues when trying to insert information to listdir.
initially, I have tried to manually put in the info:
for file in os.listdir(r'H:\My Documents')
where I get this error: [Errno 2] No such file or directory: 'H:\\My Documents'
then the below
list_of_directory = r'H:\My Documents'
for file in os.listdir(list_of_directory):
to which I got the same error.
I have tried everything including the solution mentioned here Error with double backslash in Windows path in Python but it wouldn't work.
can you please help? The rest of the code is ready and it's so frustrating that it has to wait due to this glitch!
Solution 1:[1]
Did you mean to catch the file not found error:
list_of_directory = r'H:\My Documents'
try:
for file in os.listdir(list_of_directory):
...
except FileNotFoundError:
print(list_of_directory, "not found")
This will allow the program to continue and do something else when the folder does not exist.
Solution 2:[2]
You should just be able to use a forwards slash instead on any OS, because the os library replaces forwards slahes with baclwards slashes for Windows. If that doesn't work, you could try using the pathlib library.
from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
If you wanted, you could even use pathlib to convert a Unix to a Windows path.
from pathlib import Path, PureWindowsPath
filename = Path("source_data/text_files/raw_data.txt")
path_on_windows = PureWindowsPath(filename)
So your code would become:
from pathlib import Path
list_of_directory = Path('H:/My Documents').resolve()
for file in os.listdir(list_of_directory):
print(file)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | quamrana |
| Solution 2 |
