习题4:把一个文件内容中的boy替换成xxx
with open('e:\\aaa.txt','r+',encoding='utf-8')as fp:
content=fp.read()
content=content.replace('boy','xxx')
fp.seek(0,0)
fp.write(content)
with open('e:\\aaa.txt','r+',encoding='utf-8')as fp:
content=fp.readlines()
fp.seek(0,0)
for line in content:
fp.write(line.replace('boy','xxx'))
习题5:一个文件拆分成5个文件
file_obj1 = open("e:\\a.txt","r",encoding="utf-8")
file_no = 1
file_line = 0
backup_content = ""
for line in file_obj1:
file_line += 1
backup_content += line
if file_line %2 ==0:
with open("e:\\test"+str(file_no)+".txt","w",encoding="utf-8") as file_obj2:
file_obj2.write(backup_content)
file_no += 1
backup_content = ""
习题6:过滤掉一个文件中空行
with open('e:\\a.txt','r',encoding='utf-8')as fp:
for line in fp:
if line.strip()=='':
continue
with open('e:\\33.txt','a',encoding='utf-8')as fp:
fp.write(line)
习题7:处理数据文件
with open('e:\\a.txt','r',encoding='utf-8')as fp:
content=fp.readlines()
for line in content:
with open('e:\\'+line[:14]+'.txt','w',encoding='utf-8')as fp:
fp.write(line[14:])
with open('e:\\a.txt','r',encoding='utf-8')as fp:
for line in fp:
file_name=line[:14]+'.txt'
file_content=line[14:]
with open('e:\\'+file_name,'w',encoding='utf-8') as fp:
fp.write(file_content)