python edit file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import re
import os
import os.path

dirpath = 'F:\\Users'
pattern = '</head>'
css = '<link rel="stylesheet" href="./style.css"></head>'

for file in os.listdir(dirpath):
# read all text
origin = open(os.path.join(dirpath, file), 'r+').readlines()
# edit target line
origin[0] = re.compile(pattern).sub(css, origin[0])
# rewrite whole file
open(os.path.join(dirpath, file), 'w+').writelines(origin)
  1. os.listdir(dir) list single node’s sub directory
  2. os.path.join(a, b) conbine two path string
  3. re.compile(pattern).sub(result, src) replace string