Python-文件不存在

2024-05-19 12:05:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

现在我只能在一列中找到最大值,因为我正在读取的文件有两行,我想忽略它们。很遗憾,尝试运行代码时出现以下错误:

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)

Tags: 文件代码inimportfordataosas
2条回答

要打开文件,需要指定完整路径。你得换线

with open(file) as f:

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

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

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只是文件名,指向它的路径是ommitted。这就是为什么您需要将它与来自os.walk的第一个返回参数连接起来。

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

相关问题 更多 >

    热门问题