Reputation: 485
I want to open a csv file in my windows path ..\labels.csv, yet, in the open function, it modifies my path to ..\\labels.csv so it can't find my file, why ?
I have this code :
print("..\\labels.csv")
with open(r"..\labels.csv") as csv_file:
#Some code
It gives me this error :
File "src\win_labelling.py", line 144, in <module>
with open(r"..\labels.csv") as csv_file:
FileNotFoundError: [Errno 2] No such file or directory: '..\\labels.csv'
Upvotes: 0
Views: 1708
Reputation: 1053
There are 3 things wrong with your code, the first is that you are not defining your current directory or either importing the csv module.
The second is that if you are opening a local file (in the same folder as your executable), you don't need to add the ..\
, this is usually only used when you have a file in another folder. So, what is happening with your code is: the open
function converts your path to a str
and already adds \
to the start. As you are inserting the "..\ labels.csv"
, open will form the string "\" + "\ labels.csv"
becoming ".. \\ labels"
and leading to the error FileNotFound
since there's no directory (path) with that name.
The third is that it is not clear whether you want to read or write to the file. As you put the 'r' before, I believe it is read, so the syntax is wrong. The correct code would be:
import os
import csv
# Your Absolute Path
os.path.dirname(os.path.abspath(__file__))
# If your labels.csv is in the same folder
with open("labels.csv", newline='') as csv_file:
#Some code
I advise looking at the csv documentation if you want to perform another action with your csv file, and how the path module works in python.
Upvotes: 0