Python:遍历打开的文件

标签 python arrays fwrite

如果有人能指出我正确的方向,我将不胜感激。我正在寻找替换以下内容:

file1 = open ('filepath')
file1.write(data1)
file2 = open ('filepath2')
file2.write(data2)
file3 = open ('filepath3')
file3.write(data3)

像这样可以迭代:

file[i] = open ('filepath')
file[i].write(data[i])

它们都需要不同的名称的原因是因为所有文件必须立即打开而不关闭。这只是系统的要求。

有什么办法可以做到这一点吗?

最佳答案

open_files = [open(fname) for fname in ['filepath1', 'filepath2', 'filepath3']]

for fh in open_files:
    fh.write(...)

for i, fh in enumerate(open_files):
    fh.write(data[i])

关于Python:遍历打开的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31862169/

相关文章:

python - 在 Python 密码学库中提取模数 n、私有(private)指数和公共(public)指数

arrays - Excel VBA 查找数组中的最后一个条目(但不在电子表格中)

c - 尝试从二进制文件读取足够字节时出现问题

c# - 找不到类型或命名空间列表<>

PHP:fwrite 在 foreach 循环中不起作用(由于图像链接?)

c - 错误: No such file or directory

python - 在 gui 中更新 matplotlib 图的有效方法?

python - 图灵机欧几里得求最大公约数的算法 python

python - 如何从该函数内部在 Python 中将函数名称打印为字符串

javascript - Chartjs 的多个气泡图数据集