Python小程序 - 替换文件内容
1. 写入文件c:\a.txt
1)共写入10行
2)每行内容 0123456789
# 1
ls = '0123456789'
ln = 10
with open("c:/a.txt", 'w+',encoding='UTF-8') as f:
for i in range(ln):
f.write(ls+'\n')
########################################
# 2
ln = 10
with open("c:/a.txt", 'w+',encoding='UTF-8') as f:
for i in range(ln):
ls = str(i)
for j in range(ln):
ls = ls + str(j)
f.write(ls+'\n')
##
00123456789
10123456789
20123456789
30123456789
40123456789
50123456789
60123456789
70123456789
80123456789
90123456789
2. 替换文件内容
1)全文替换指定内容
# replace '1' with 'a'
# 1
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
fl = f.readlines()
for fs in fl:
print(fs.replace('1','a'))
###############################################
# 2-1
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
fl = f.readline()
while fl:
print(fl.replace('1','a'))
fl = f.readline()
# 2-2
fl = ''
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
fl = f.readlines()
for fn in range(len(fl)):
print(fl[fn].replace('1','a'))
fl[fn] = fl[fn].replace('1','a')
print(fl[fn])
with open("c:/a.txt", 'w',encoding='UTF-8') as f:
f.writelines(fl)
####
00a23456789
a0a23456789
20a23456789
30a23456789
40a23456789
50a23456789
60a23456789
70a23456789
80a23456789
90a23456789
2)替换指定行的内容
# replace line 5
# replace '1' with 'A'
rl = 5
rw = 'A'
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
fl = f.readlines()
fl[rl-1] = fl[rl-1].replace('1',rw)
with open("c:/a.txt", 'w',encoding='UTF-8') as f:
f.writelines(fl)
##
00123456789
10123456789
20123456789
30123456789
40A23456789
50123456789
60123456789
70123456789
80123456789
90123456789
3. 定义函数
def replace_word_in_file(file_path,old_word,new_word,line_num):
fl = '' # file content
with open(file_path, 'r',encoding='UTF-8') as f:
fl = f.readlines()
if(line_num>len(fl) or line_num<0 ):
print('Wrong line number, pleae check.')
# replace all in file
elif(line_num == 0):
for fn in range(len(fl)):
fl[fn] = fl[fn].replace(old_word,new_word)
else:
fl[line_num-1] = fl[line_num-1].replace(old_word,new_word)
with open(file_path, 'w',encoding='UTF-8') as f:
f.writelines(fl)
if __name__ == "__main__":
replace_word_in_file("c:/a.txt",'1','A',0) # 1
replace_word_in_file("c:/a.txt",'1','A',5) # 2
replace_word_in_file("c:/a.txt",'1','A',11) # 3
replace_word_in_file("c:/a.txt",'1','A',-1) # 4
## 1
00A23456789
A0A23456789
20A23456789
30A23456789
40A23456789
50A23456789
60A23456789
70A23456789
80A23456789
90A23456789
## 2
00123456789
10123456789
20123456789
30123456789
40A23456789
50123456789
60123456789
70123456789
80123456789
90123456789
## 3
Wrong line number, pleae check.
## 4
Wrong line number, pleae check.
-- 创作助手提问
- python readline 逐行读出
with open('file.txt', 'r') as file: line = file.readline() while line: print(line) line = file.readline()
- python 写入文件
# 打开文件,以写入模式('w')进行操作 file = open('example.txt', 'w') # 写入文本 file.write('Hello, world!') # 关闭文件 file.close()