Python - File does not exist error

2019-09-04 04:57发布

问题:

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 second thing was to open a specific file (it is the same name in each subdirectory) and find the minimum and maximum value in each column EXCEPT the first.

Right now I'm stuck on finding the max value in a single column because the files I'm reading have two rows which I want to ignore. Unfortunately, I'm getting the following error when attempting to run the code:

Traceback (most recent call last):
  File "test_script.py", line 22, in <module>
    with open(file) as f:
IOError: [Errno 2] No such file or directory: 'tc.out'

Here is the current state of my code:

import scipy as sp
import os

rootdir = 'mydir'; #mydir has been changed from the actual directory path
data = []

for root, dirs, files in os.walk(rootdir):
    for file in files:
        if file == "tc.out":
            with open(file) as f:
                for line in itertools.islice(f,3,None):
                    for line in file:
                    fields = line.split()
                    rowdata = map(float, fields)
                    data.extend(rowdata)
                    print 'Maximum: ', max(data)

回答1:

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:

with open(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 in os.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


回答2:

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

with open(file) as f:

to

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