Python 同时打开列表中的所有文件
我需要修改(可变但很少)数量的文件,我想知道是否有Python语法允许我在Python 同时打开列表中的所有文件,python,python-2.x,Python,Python 2.x,我需要修改(可变但很少)数量的文件,我想知道是否有Python语法允许我在with语句中打开它们。比如说 file_names = ("file_a", "file_b", "file_c") with open(file_names) as files: for file_ in files: file_.write("Hello file!") 在本例中,文件名的长度将有所不同。实际上,它支持以下语法: with open("file_a", "r+") as
with
语句中打开它们。比如说
file_names = ("file_a", "file_b", "file_c")
with open(file_names) as files:
for file_ in files:
file_.write("Hello file!")
在本例中,文件名的长度将有所不同。实际上,它支持以下语法:
with open("file_a", "r+") as fa, open("file_b", "r+") as fb, \
open("file_c", "r+") as fc:
for f in (fa, fb, fc):
f.write("Hello file!")
要在不同数量的上下文管理器上使用和
,您至少需要Python 3.3和。实际上,它支持以下语法:
with open("file_a", "r+") as fa, open("file_b", "r+") as fb, \
open("file_c", "r+") as fc:
for f in (fa, fb, fc):
f.write("Hello file!")
要在不同数量的上下文管理器上使用和
,您至少需要Python 3.3和。注意,您需要以某种形式的写入权限打开文件,以便。写入
才能工作…注意,您需要以某种形式的写入权限打开文件,以便。写入
才能工作。。。