python将指定文本中的字符串替换后,生成新的文本文件。

Python替换某个文本中的字符串,然后生成新的文本文档,代码如下:import osos.chdir('D:\\') # 跳到D盘if not os.path.exists('test1.txt'): # 看一下这个文件是否存在exit(-1) #不存在就退出lines = open('test1.txt').readlines() #打开文件,读入每一行fp = open(''test2...
python将指定文本中的字符串替换后,生成新的文本文件。
import os

os.chdir('d:\\') # 跳到D盘

if not os.path.exists('pp.txt'): # 看一下这个文件是否存在
exit(-1) #,不存在就退出

lines = open('pp.txt').readlines() #打开文件,读入每一行

fp = open('pp2.txt','w') #打开你要写得文件pp2.txt
for s in lines:
fp.write( s.replace('love','hate').replace('yes','no')) # replace是替换,write是写入
fp.close() # 关闭文件2012-07-14
Python替换某个文本中的字符串,然后生成新的文本文档,代码如下:
import osos.chdir('D:\\') # 跳到D盘if not os.path.exists('test1.txt'): # 看一下这个文件是否存在exit(-1) #不存在就退出lines = open('test1.txt').readlines() #打开文件,读入每一行fp = open(''test2.txt','w') #打开你要写得文件test2.txtfor s in lines:# replace是替换,write是写入fp.write( s.replace('love','hate').replace('yes','no')) fp.close() # 关闭文件2015-07-07
infile = open("D:/pp.txt", "r") #打开文件
outfile = open("D:/pp2.txt", "w") # 内容输出

for line in infile: #按行读文件,可避免文件过大,内存消耗
outfile.write(line.replace('love', 'hate').replace('yes','no'))
infile.close() #文件关闭
outfile.close()2012-07-16
mengvlog 阅读 307 次 更新于 2025-12-19 16:11:31 我来答关注问题0
檬味博客在线解答立即免费咨询

Python相关话题

Copyright © 2023 WWW.MENGVLOG.COM - 檬味博客
返回顶部