python - 如何在循环中打开多个文件,在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。我应该怎么办?
解决方案
像打开一个一样打开每个,然后将它们附加到一个列表中:
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"
. 然后,您可以像上面的脚本一样获取文件的所有文件路径。
推荐阅读
- c - 程序不会从用户那里获取输入来再次循环自己。
- reactjs - 如何在 React Component 中保留初始状态?
- python-3.x - miniconda 解决环境:ubuntu 失败
- sql - SQL 视图 - 获取单价、默认价格和客户价格
- recursion - 这两个定义是相同的还是不同的
- javascript - 使用 CDN 与 NPM/Yarn 进行依赖的优缺点是什么?
- regex - 如何在 PostgreSQL 中提取数字后跟特定字符串?
- firebase - firebase auth 需要关于 twitter 的什么样的许可?(读,读,写,...)
- sql - 在缺少记录的 SQLite 中进行透视
- javascript - Typescript - 手动刷新文本区域