【问题标题】:Error in reading file python [duplicate]读取文件python时出错[重复]
【发布时间】:2014-01-22 12:12:30
【问题描述】:

我正在尝试在一个目录中读取我的 python 文件。我收到一个错误

Traceback (most recent call last):
  File "/home/akallararajappan/codes to handle unicode/read_directory.py", line 42, in <module>
    open_file( filename)
  File "/home/akallararajappan/codes to handle unicode/read_directory.py", line 31, in open_file
    data = open (fil_name, 'r').read()
IOError: [Errno 2] No such file or directory: 'createFile.py' 

这是我的代码:

import os
import codecs
def open_file(fil_name) :
    data = open (fil_name, 'r').read()
    print data 



for dirname, dirnames, filenames in os.walk('/home/akallararajappan/corpus'):
    print()
    #print(dirname + ":")
    for filename in filenames:
        open_file( filename)

这里有什么问题?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    os.walk() 中的文件名没有有完整路径;它们总是相对于dirname。在尝试打开文件之前先添加dirname 路径:

    for dirname, dirnames, filenames in os.walk('/home/akallararajappan/corpus'):
        for filename in filenames:
            open_file(os.path.join(dirname, filename))
    

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 2013-07-11
      • 2018-05-31
      • 2011-08-22
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多