无法从 python 目录中打开文件 [英] Can't Open files from a directory in python

查看:87
本文介绍了无法从 python 目录中打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written a small module that first finds all the files in the directory, and merge them. But, I'm having the problem with opening these files from a directory. I made sure that my files and directory names are correct, and files are actually in the directory.

下面是代码..

 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 您需要完整路径才能打开文件.在打开它之前还要检查以确保它是一个文件.示例代码如下.

listdir returns just the file names: https://docs.python.org/2/library/os.html#os.listdir You need the fullpath to open the file. Also check to make sure it is a file before you open it. Sample code below.

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/教程/inputoutput.html#methods-of-file-objects 细节和例子

However for files it is better to open using the with keyword. It handles closing for you even when there are exceptions. See https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for details and an example

这篇关于无法从 python 目录中打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆