Python 循环浏览目录/文件夹中的文件,过滤它们,然后逐行从中读取信息
我想循环浏览文件夹中的文件,并从中读取一些数据:Python 循环浏览目录/文件夹中的文件,过滤它们,然后逐行从中读取信息,python,python-3.x,file,Python,Python 3.x,File,我想循环浏览文件夹中的文件,并从中读取一些数据: directory = os.fsencode(directory) for file in os.listdir(directory): file = os.fsdecode(file) if file.endswith(".log"): with open(file) as f: for line in f:
directory = os.fsencode(directory)
for file in os.listdir(directory):
file = os.fsdecode(file)
if file.endswith(".log"):
with open(file) as f:
for line in f:
extract(line=line))
打开(文件)为f:FileNotFoundError:[Errno 2]没有此类文件或
目录:b'access.log'
这很奇怪,因为文件存在。您需要将基本路径添加到文件中。使用
os.path.join(目录、文件)
Ex:
directory = os.fsencode(directory)
for file in os.listdir(directory):
file = os.fsdecode(file)
if file.endswith(".log"):
with open(os.path.join(directory, file)) as f:
for line in f:
extract(line=line))
我得到一个错误:不能在路径组件中混合字符串和字节。我使用Python3.7,如果我为join保留一个目录版本,而不是编码的,它就可以工作