鱼C论坛

 找回密码
 立即注册
查看: 2217|回复: 2

[已解决]二问:python在文件路径中可以添加格式化字符串吗?

[复制链接]
发表于 2020-9-22 22:02:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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同样操作?(不复制代码)
谢谢大佬
最佳答案
2020-9-22 22:26:00
  1. file1=['a-01.txt',  'b-01.txt', 'c-01.txt']
  2. file2=['a-02.txt',  'b-02.txt', 'c-02.txt']
  3. for i in range(len(file1)):
  4.     with open(r'C:\(路径)\%s'%file1[i], encoding='utf-8') as a,\
  5.          open(r'C:\(路径)\%s'%file2[i], mode='x' ,encoding='utf-8') as n:
  6.         space = []
  7.         repeat = []
  8.         for line in .readlines():
  9.             if line not in space:
  10.                 space.append(line)
  11.             else:
  12.                 repeat.append(line)
  13.         z = [i for i in space if i not in repeat]
  14.         result = ''.join(z)
  15.         n.write(result)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-9-22 22:26:00 | 显示全部楼层    本楼为最佳答案   
  1. file1=['a-01.txt',  'b-01.txt', 'c-01.txt']
  2. file2=['a-02.txt',  'b-02.txt', 'c-02.txt']
  3. for i in range(len(file1)):
  4.     with open(r'C:\(路径)\%s'%file1[i], encoding='utf-8') as a,\
  5.          open(r'C:\(路径)\%s'%file2[i], mode='x' ,encoding='utf-8') as n:
  6.         space = []
  7.         repeat = []
  8.         for line in .readlines():
  9.             if line not in space:
  10.                 space.append(line)
  11.             else:
  12.                 repeat.append(line)
  13.         z = [i for i in space if i not in repeat]
  14.         result = ''.join(z)
  15.         n.write(result)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-9-22 23:42:23 | 显示全部楼层
谢谢大佬!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-27 18:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表