0

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

  1. the file is in the same directory as the Python code accessing the file
  2. No matter whether I use the relative or absolute path, I get this error
  3. I tried: import sys sys.path.append(r'C:/Users/Owner/Documents/Research/SomaStuhl') but still got Errno 2

New Python user

2
  • Did you try copy and pasting the link in windows file explorer to see if it opens correctly? Commented Apr 1, 2022 at 20:43
  • Add code snippet Commented Apr 1, 2022 at 20:43

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Very detailed. I will work on this tomorrow
Thank you, everyone one for these answers.
Thank you, everyone for these answers. I went for simplest first, looking for the file. Although it was in my Windows 10 Explorer directory, when I used cd, change directory, I got message "Name is nonexistent or not a folder". I changed the name of the folder from SomaStuhl to SOMA. When I opened the file in Matlab or Python with the path: C:\Users\Owner\Research\SOMA\SomaFinal.csv, I was able to access the file. I have no idea why the folder name SomaStuhl didn't exist but the folder SOMA does. Thanks again. I

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.