二问:python在文件路径中可以添加格式化字符串吗?
我想要打开三个名字格式相似的文件,并且进行除了文件名以外完全相同的操作。如果把相似代码复制三次的话,会显得很冗长……请问这样有什么解决方案,是使用格式化字符串吗?具体要求:分别打开a-01.txt,b-01.txt,c-01.txt,提取其中未重复的内容,分别写入新创建的同目录的a-02.txt,b-02.txt,c-02.txt中。
我设置的代码如下:
with open(r'C:\(路径)\a-01.txt', encoding='utf-8') as a,\
open(r'C:\(路径)\a-02.txt', mode='x' ,encoding='utf-8') as n:
space = []
repeat = []
for line in .readlines():
if line not in space:
space.append(line)
else:
repeat.append(line)
z =
result = ''.join(z)
n.write(result)
这只针对a进行了操作,如何让它对b,c同样操作?(不复制代码)
谢谢大佬 file1=['a-01.txt','b-01.txt', 'c-01.txt']
file2=['a-02.txt','b-02.txt', 'c-02.txt']
for i in range(len(file1)):
with open(r'C:\(路径)\%s'%file1, encoding='utf-8') as a,\
open(r'C:\(路径)\%s'%file2, mode='x' ,encoding='utf-8') as n:
space = []
repeat = []
for line in .readlines():
if line not in space:
space.append(line)
else:
repeat.append(line)
z =
result = ''.join(z)
n.write(result) 谢谢大佬!
页:
[1]