Search code examples
pythonfilenotfounderror

Getting a FileNotFoundError, despite directory existing


I'm trying to loop through files in a directory, but I keep getting a file not found error, despite the fact the directory is literally copy-pasted from Windows explorer. It's not stored in the C drive, so might that be the problem?

Here's the code.

# Setting directory
obj_path = "D:/ultivue/1604-2201 Core 8plex (All Runs) Region Object Data/run 2"

# For loop to go through all files in the path
for file in obj_path:
    data = pd.read_csv(file)

And here's the error.

FileNotFoundError: [Errno 2] No such file or directory: 'D'

Solution

  • Strings are iterables in Python, which means they can be looped over. So something like for char in 'word': print(char) will print each character of 'word' individually.

    As written, you're trying to iterate over the string obj_path with for _ in, which is why it's stopping at 'D' (the first letter of the string) and throwing an error when it tries to open that as a csv.

    You can use the pathlib module's iterdir() method to iterate over all the files in a given directory

    import pathlib
    
    # Setting directory (instantiate as a pathlib.Path object)
    obj_path = pathlib.Path("D:/ultivue/1604-2201 Core 8plex (All Runs) Region Object Data/run 2")
    
    # For loop to go through all files in the path
    for file in obj_path.iterdir():
        data = pd.read_csv(file)
        # do something with 'data' here, as it's going to be overwritten
        # on each loop iteration!