Skip to content Skip to sidebar Skip to footer

Python - File Does Not Exist Error

I'm trying to do a couple things here with the script below (it is incomplete). The first thing is to loop through some subdirectories. I was able to do that successfully. The seco

Solution 1:

To open a file you need to specify full path. You need to change the line

withopen(file) as f:

to

withopen(os.path.join(root, file)) as f:

Solution 2:

When you write open(file), Python is trying to find the the file tc.out in the directory where you started the interpreter from. You should use the full path to that file in open:

withopen(os.path.join(root, file)) as f:

Let me illustrate with an example:

I have a file named 'somefile.txt' in the directory /tmp/sto/deep/ (this is a Unix system, so I use forward slashes). And then I have this simple script which resides in the directory /tmp:

oliver@armstrong:/tmp$ cat myscript.py
import os

rootdir = '/tmp'for root, dirs, files inos.walk(rootdir):
    for fname in files:
        if fname == 'somefile.txt':
            with open(os.path.join(root, fname)) as f:
                print('Filename: %s' % fname)
                print('directory: %s' % root)
                print(f.read())

When I execute this script from the /tmp directory, you'll see that fname is just the filename, the path leading to it is ommitted. That's why you need to join it with the first returned argument from os.walk.

oliver@armstrong:/tmp$ python myscript.py
Filename: somefile.txt
directory: /tmp/sto/deep
contents

Post a Comment for "Python - File Does Not Exist Error"