|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我想要打开三个名字格式相似的文件,并且进行除了文件名以外完全相同的操作。如果把相似代码复制三次的话,会显得很冗长……请问这样有什么解决方案,是使用格式化字符串吗?
具体要求:分别打开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 = [i for i in space if i not in repeat]
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[i], encoding='utf-8') as a,\
- open(r'C:\(路径)\%s'%file2[i], 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 = [i for i in space if i not in repeat]
- result = ''.join(z)
- n.write(result)
复制代码
|
|