循环遍历python中的文件夹并打开文件会引发错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42683517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
loop through folder in python and open files throws an error
提问by Moe Siddig
I try to loop through folder and read files but only the first file will open and read correctly but the second files print the name and through an error "IOError: [Errno 2] No such file or directory:". I have tried the following
我尝试遍历文件夹并读取文件,但只有第一个文件会打开并正确读取,但第二个文件会打印名称并通过错误“IOError:[Errno 2] 没有这样的文件或目录:”。我已经尝试了以下
for filename in os.listdir("pathtodir\DataFiles"):
if filename.endswith(".log"):
print(os.path.join("./DataFiles", filename))
with open(filename) as openfile:
for line in openfile:
........
回答by mdh
os.listdir()
gives you only the filename, but not the path to the file:
os.listdir()
只给你文件名,而不是文件的路径:
import os
for filename in os.listdir('path/to/dir'):
if filename.endswith('.log'):
with open(os.path.join('path/to/dir', filename)) as f:
content = f.read()
Alternatively, you could use the glob
module. The glob.glob()
function allows you to filter files using a pattern:
或者,您可以使用该glob
模块。该glob.glob()
函数允许您使用模式过滤文件:
import os
import glob
for filepath in glob.glob(os.path.join('path/to/dir', '*.log')):
with open(filepath) as f:
content = f.read()
回答by James
Using os.listdir(...)
only returns the filenames of the directory you passed, but not the full path to the files. You need to include the relative directory path as well when opening the file.
Usingos.listdir(...)
仅返回您传递的目录的文件名,而不是文件的完整路径。打开文件时,您还需要包含相对目录路径。
basepath = "pathtodir/DataFiles/"
for filename in os.listdir(basepath):
if filename.endswith(".log"):
print(os.path.join("./DataFiles", filename))
with open(basepath + filename) as openfile:
for line in openfile:
........