Python - 文件不存在错误

问题描述 投票:0回答:2

我正在尝试使用下面的脚本做一些事情(它是不完整的)。首先是遍历一些子目录。我能够成功地做到这一点。第二件事是打开一个特定的文件(它在每个子目录中是相同的名称),并在每列中找到最小值和最大值,除了第一列。

现在我一直坚持在单个列中找到最大值,因为我正在阅读的文件有两行我想忽略。不幸的是,我在尝试运行代码时遇到以下错误:

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'

这是我的代码的当前状态:

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)
python directory max min
2个回答
1
投票

当你编写open(file)时,Python正试图在你启动解释器的目录中找到文件tc.out。您应该在open中使用该文件的完整路径:

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

让我用一个例子来说明:

我在/tmp/sto/deep/目录中有一个名为'somefile.txt'的文件(这是一个Unix系统,所以我使用正斜杠)。然后我有这个简单的脚本,它位于/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())

当我从/tmp目录执行这个脚本时,你会看到fname只是文件名,省略了通向它的路径。这就是为什么你需要加入os.walk的第一个返回的参数。

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

1
投票

要打开文件,您需要指定完整路径。你需要改变这条线

with open(file) as f:

with open(os.path.join(root, file)) as f:
© www.soinside.com 2019 - 2024. All rights reserved.