IOError:[Errno 2]没有这样的文件或目录:'0.txt'

时间:2016-06-21 04:08:51

标签: python

我正在编写一个程序来读取文件夹“set”中的一组文本文件到列表。我的代码是

def get_documents():
    path1 = "D:/set/"
    texts = []
    listing1 = os.listdir(path1)
    for file in listing1:
        with open(file,'r') as f:
            lines = f.read().splitlines()
            texts.append(lines)

但是这给了我错误

with open(file,'r') as f:
IOError: [Errno 2] No such file or directory: '0.txt'

D:/set/内有0.txt,1.txt,2.txt...文字文件 这个错误的原因是什么?

1 个答案:

答案 0 :(得分:2)

函数open()返回目录中的文件名,而不是with open(os.path.join(path1, file),'r') as f: ... 所期望的完整路径。

您可以通过将基本路径连接到文件名来解决此问题。

glob()

另一种方法是使用import glob path1 = "D:/set/*" listing1 = glob.glob(path1) for file in listing1: with open(file,'r') as f: ... 来避免路径加入:

With Application
     .EnableEvents = False
     .ScreenUpdating = False
 End With
Application.DisplayAlerts = False
m.SaveAs savePath, olTXT 
With Application
     .EnableEvents = True
     .ScreenUpdating = ture
End With
相关问题