我正在尝试在目录中读取我的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)
这里有什么问题?
答案 0 :(得分:5)
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))