I receive this error: FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Owner/Documents/Research/SomaStuhl/SomaFinal.csv'
I've read thru several stackoverflow answers for this problem
- the file is in the same directory as the Python code accessing the file
- No matter whether I use the relative or absolute path, I get this error
- I tried: import sys sys.path.append(r'C:/Users/Owner/Documents/Research/SomaStuhl') but still got Errno 2
New Python user
CodePudding user response:
In order to make sure that what you are trying to access exists, do the following:
import csv
from pathlib import Path
# Navigate from the file explorer, copy the path and assign it as a path to a variable.
# We are using Path object because it automatically recognizes windows paths
my_path = Path("C:/Users/username/Documentd/Research/SomaStuhl")
# Then check if it exists
my_path.exists()
# if the output is True it means it found the path
# then try to list the items of that directory to make sure it is there
list(my_path.iterdir())
# if it is there read it like that just to be sure it works with the built-ins
# we will use joinpath to make sure we correctly extend from the existing path and enumerate to emulate the bash command
# head SomaFinal.csv -n5
# the with statement means it will close the file when it finishes reading the file
with my_path.joinpath('SomaFinal.csv').open() as f:
reader = csv.reader(f)
# idx comes from enumerate and row from reader, 1 means start counting from 1
for idx, row in enumerate(reader, 1):
print(row)
if idx == 5:
break
CodePudding user response:
Are you using vscode? if you do, try to open the whole directory in the workspace, not just the file. I used to have the same issue and this is how I solved it.