python批量修改文件某行内容

Python很强大,用来做一些批处理非常便捷。如今又遇到了一批MD文件需要删除或者替换某行的内容,当然行内有固定的关键字,可以用来定位行。

由于文件都比较小,可以一次都读入内存,因此思路是

  • 先把所有内容读取到list,
  • 然后依次对每行查询关键词并替换掉关键词,
  • 最后把修改后的list覆盖保存到源文件。

本次进行批量处理的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
rootpath = 'folder_path'
ext='.md'
replace='keyword'

filelists = os.listdir(rootpath)
for filename in filelists:
if filename.endswith(ext):
filepath = os.path.join(rootpath, filename)
print(filepath)
newlines = []
f = open(filepath, 'r', encoding='utf8')
for line in f.readlines():
if line.find(replace) > -1 :
print(line)
else:
newlines.append(line)
f.close()

with open(filepath, 'w', encoding='utf8') as f:
f.writelines(newlines)
print(filepath + ' --OK')

进阶版1

对于大文件的话,这种全部读出来的方式就不行了,可能会造成内存溢出。对于大文件可以采用’读取一行(或一定量的数据)、处理一行、保存一行‘的方式,建立临时文件,将处理过的数据保存到临时文件,然后再把临时文件改名为源文件,具体为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os
filepath='file.md'
nfilepath='file.md.temp'

nf=open(nfilepath, 'w', encoding='utf8')
with open(filepath, 'r', encoding='utf8') as f:
for line in f:
if line=='\n':
pass
else :
nf.write(line)
nf.close()

os.replace(nfilepath,filepath)
但是这样也有缺点,会临时造成硬盘空间的大量占用,当硬盘写满后就会保存失败

进阶版2

对于内存和硬盘空间都有严格要求的应用,就只能用文件指针的偏移来修改文件了,即seek()方法。使用时要小心计算seek到正确的位置,而且替换数据时要注意字节长度,不要覆盖后面的内容。

虽然很不要脸,但是还请您多多打赏 ^_^