0

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'
2
  • The path is not modified. "..\\labels.csv" is a string literal that creates a string with only one backslash. Doubling a backslash is the way to escape it in a string literal. Commented Jul 8, 2020 at 2:07
  • Probably the working directory is not what you expect it to be. Check import os; print(os.getcwd()). Commented Jul 8, 2020 at 2:09

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

My script is running in "test\src\" and I'm trying to open a file located in "test\". In ubuntu I use "../" to be in the higher folder but I don't think it's working on windows
If you are using windows try to use '..' instead of '../' then, I think this should solve your problem. Another solution is use the pathlib module, he will be handy when working with windows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.