python练习六十三:文件处理
假设要读取code.txt文件中内容,code.txt文件内容如下
01 CN Chinese
02 US United States of America
03 JP Japan
04 HK Hongkang
05 IN India
文件名称:01CNChinese.txt
文件内容:01 CN Chinese

写文件(如果有文件,那直接调用就行,我这里自己先创建的文件)

list1 = ['01 CN Chinese','02 US United States of America','03 JP Japan','04 HK Hongkang','05 IN India']
with open('code.txt','w+') as f:
    for i in list1:
        f.write(i+'\n')

初始版:

suffix = '.txt'
with open('code.txt','r') as f:
    f_connect = f.readlines()
    while True:
        if not f_connect:
            break
        for i in f_connect:
#             new_i = (i.replace(' ','')).replace('\n','')+suffix  #剔除空格和换行
            new_i = (''.join(i.split(' '))).replace('\n','')+suffix  #剔除空格和换行
            with open(new_i,'w') as f:
                f.write(i)

初始版:存在问题:结束不了,文件反复的进行写操作

改进版:

suffix = '.txt'
with open('code.txt','r') as f:
    while True:
        f_connect = f.readlines()
        if not f_connect:
            break
        for i in f_connect:
#             new_i = (i.replace(' ','')).replace('\n','')+suffix  #剔除空格和换行
            new_i = (''.join(i.split(' '))).replace('\n','')+suffix  #剔除空格和换行
            open(new_i,'w').write(i)

结果:

python练习六十三:文件处理,读取文件内容,按内容生成文件

相关文章:

  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2021-11-10
  • 2022-12-23
猜你喜欢
  • 2021-07-03
  • 2021-11-27
  • 2022-12-23
  • 2022-02-28
  • 2022-12-23
  • 2021-06-01
相关资源
相似解决方案