Python文件读写 - 读一个文件所有行,加工后写另一个文件

时间:2021-06-27 05:29:16
 #Filename: file_read_and_write.py
#打开文件,cNames读取所有行,储存在列表中,循环对每一行在起始处加上序号1,2,3,4
with open(r'file/companies.txt') as f1:
cNames = f1.readlines()
for i in range(0,len(cNames)):
cNames[i] = str(i+1) + '.' + '' + cNames[i] #将处理过的cNames写入新的文件中
with open(r'file/scompanies.txt','w') as f2:
f2.writelines(cNames)

输入: companies.txt

google
tencent
alibaba
baidu

输出:scompanies.txt

1.google
2.tencent
3.alibaba
4.baidu