简体   繁体   中英

FileNotFoundError: [Errno 2] No such file or directory. Python not reading files correctly

I am having some troubles when trying to open a file in the same directory. When I open the file it brings me up this error:

Traceback (most recent call last):
File "c:/Users/joseph/Desktop/direct path/test_path.py", line 3, in <module> 
with open("nba_reports.csv","r") as file:
FileNotFoundError: [Errno 2] No such file or directory: nba_reports.csv

When in reality that file named 'nba_reports.csv' is right next to where the python file is saved. I have had this problem in various different IDEs, I'm currently working on Visual Code and Visual Studio and I have managed to solve the problem by specifying the complete path from the file as "c:/Users/joseph/Desktop/direct path/nba_reports.csv". However, when I open this same code on Thonny it does recognize the file with no problem at all just by specifying the file name. I would really appreciate if someone could help me out with this problem so that I can just write the file name on Visual Code.

The code is as followed:

with open("nba_reports.csv","r") as file:
    for row in file:
        print(row)

You can use the os library to get the current working directory with

os.getcwd()

It's likely if you print the result of that, it will show Python isn't using the proper working directory. To change it. use os.chdir() as follows. The parameter you should give os.chdir follows the way you would use the cd command from the command line in a Unix based operating system.

>>> import os
>>> os.getcwd()
'/Users/myname'
>>> os.chdir('./Documents')
>>> os.getcwd()
'/Users/name/Documents'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM