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同样操作?(不复制代码)
谢谢大佬{:10_254:} {:10_254:} {:10_254:}
temp=97 # 这是'a'的ASCII码值
while temp<100:
with open(r'C:\(路径)\%c-01.txt'%temp, encoding='utf-8') as a,\
open(r'C:\(路径)\%c-02.txt'%temp, 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)
temp+=1 sunrise085 发表于 2020-9-22 22:31
谢谢大佬! sunrise085 发表于 2020-9-22 22:31
大佬,我学习了你的方法想去做另一道题,结果它只完成了对a的操作{:10_266:}
以下代码哪里错了,想了很久没想通,求教{:10_297:}
temp=97
with open (r'C:\Users\God bless CHINA\程序学习垃圾\dialog.txt',encoding='utf-8') as total:
while temp<100:
with open(r'C:\Users\God bless CHINA\程序学习垃圾\%c-01.txt'%temp,mode='w',encoding='utf-8') as m:
for words in total.readlines():
if list(words)[:2]==['%c'%temp,':']:
new=words.replace('%c:'%temp,' ')
m.write(new)
temp+=1
页:
[1]