【问题标题】:Can't Open files from a directory in python [duplicate]无法从python中的目录打开文件
【发布时间】:2014-11-21 18:54:06
【问题描述】:

我写了一个小模块,它首先找到目录中的所有文件,然后合并它们。 但是,我在从目录中打开这些文件时遇到了问题。 我确保我的文件和目录名称正确,并且文件实际上在目录中。

下面是代码..

 seqdir = "results"
 outfile = "test.txt"

 for filename in os.listdir(seqdir):
     in_file = open(filename,'r') 

以下是错误..

     in_file = open(filename,'r')     
     IOError: [Errno 2] No such file or directory: 'hen1-1-rep1.txt'

【问题讨论】:

  • 问题可能是您没有使用绝对路径 - 请参阅 isedev 刚刚发布的答案 :)

标签: python ioerror


【解决方案1】:

listdir 只返回文件名:https://docs.python.org/2/library/os.html#os.listdir 您需要完整路径才能打开文件。在打开它之前还要检查以确保它是一个文件。示例代码如下。

for filename  in os.listdir(seqdir):
    fullPath = os.path.join(seqdir, filename)
    if os.path.isfile(fullPath):
        in_file = open(fullPath,'r')
        #do you other stuff

但是对于文件,最好使用with 关键字打开。即使有异常,它也会为您处理关闭。有关详细信息和示例,请参阅https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2018-01-20
    • 2013-10-24
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多