python文件操作


-将多个文件的内容写入至一个新文件中
import os

path=r'E:xx老师]种子超大合集300多部'
new_file=r'E:xx老师]种子超大合集300多部 ew.txt'
for file_list in os.listdir(path):
with open(path+'/'+file_list,'r+') as file:
file_info=file.read()
str1='更多种子,请联系: engfish@gmail.com QQ:xx'
str2=file_info.replace(str1,'')
with open(new_file,"a+") as file2:
file2.write(str2)
思路:
定义要读取的文件目录
定义要写入的文件目录
遍历读取目前下的所有文件并打开,
将打开的文件内容保存至一个变量,将保存的变量写入至新文件


写入后效果:

# 练习1:一份文件中保存的是各位同学的各科成绩,编写程序计算出各位同  学的总成绩写入文件中每行末尾
# 保存学生成绩的文件格式
# a1 70 80 90
# a2 80 90 85
# a3 85 80 95
txt1=r'F:
ew_Lx1.txt'
txt2=r'F: ew_Lx2.txt'
#创建文件
with open(txt1,"w+") as file_txt1:
file_txt1.write('a1 70 80 90 a2 80 90 85 a3 85 80 95')
b=file_txt1.read()
file_txt1.close()
#打开文件1
with open(txt1,"r+") as file_txt2:
str1=' '
for a in file_txt2:
b=a.strip() #去掉空格
list2=b.split(str1) #将字符串转化为一个列表
c=str(int(list2[1])+int(list2[2])+int(list2[-1])) #算出总成绩
list2.append(c) #将总成绩添加至list2
# file_txt2.write(str(c))
d=str1.join(list2) #将list2转换为str,用空格作为分隔符
with open(txt2,"a+") as file_txt3: #打开文件2
file_txt3.write(d+' ') #将str的值写入文件2

 

test_file1_path=r'F:
ew11.25.txt'
str1='name,mailbox '
with open(test_file1_path,'a+') as test_file1:
test_file1.write(str1)
a=0
while a<50000:
a+=1
str2=str('vu'+str(a)+',')
str3=str('vu'+str(a)+'@163.com ')
str4=str2+str3
test_file1.write(str4)



脑子不够用当然只能脚踏实地的做事情!
原文地址:https://www.cnblogs.com/qtclm/p/10015727.html