[英]Can't Open files from a directory in python
我编写了一个小模块,该模块首先在目录中找到所有文件,然后合并它们。 但是,我从目录中打开这些文件时遇到问题。 我确保我的文件和目录名称正确,并且文件实际上在目录中。
下面是代码。
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'
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.