鱼C论坛

 找回密码
 立即注册
查看: 1742|回复: 3

[已解决]python:能否在打开文件的时候在文件路径里加入格式化字符串?

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

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

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

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:31:48
  1. temp=97 # 这是'a'的ASCII码值
  2. while temp<100:
  3.     with open(r'C:\(路径)\%c-01.txt'%temp, encoding='utf-8') as a,\
  4.          open(r'C:\(路径)\%c-02.txt'%temp, mode='x' ,encoding='utf-8') as n:
  5.         space = []
  6.         repeat = []
  7.         for line in .readlines():
  8.             if line not in space:
  9.                 space.append(line)
  10.             else:
  11.                 repeat.append(line)
  12.         z = [i for i in space if i not in repeat]
  13.         result = ''.join(z)
  14.         n.write(result)
  15.         temp+=1
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

使用道具 举报

 楼主| 发表于 2020-9-23 07:31:15 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-9-23 07:58:46 | 显示全部楼层

大佬,我学习了你的方法想去做另一道题,结果它只完成了对a的操作
以下代码哪里错了,想了很久没想通,求教
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
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

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

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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