首页 > 解决方案 > 如何在循环中打开多个文件,在python中

问题描述

我是 python 新手。我想在 Python 中打开多个文件。我可以用open()功能打开它们中的每一个。我不确定格式。

with open("/test/filename.css", "r") as f:
     s = f.readlines()
     print(s)

我可以打开一个文件,但我不确定如何打开多个文件。这是我拥有的代码。在live_filename()函数中有很多文件。

inputfiles = live_filename()
    for live in inputfiles:
        with open("/test/............. .css, "r") as f:

我不知道如何将代码格式放在空间中。我认为live变量是一个元组不能连接str。我应该怎么办?

标签: python

解决方案


像打开一个一样打开每个,然后将它们附加到一个列表中:

import os

folderpath = r"D:\my_data" # make sure to put the 'r' in front
filepaths  = [os.path.join(folderpath, name) for name in os.listdir(folderpath)]
all_files = []

for path in filepaths:
    with open(path, 'r') as f:
        file = f.readlines()
        all_files.append(file)

现在,all_files[0]保存加载的第一个文件,第二文件,依此类推。 all_files[1]


更新:对于同一文件夹中的所有文件:首先,获取文件夹路径(在 Windows 上,像这样)。假设它是"D:\my_data". 然后,您可以像上面的脚本一样获取文件的所有文件路径。


推荐阅读