# |- a X& o y _6 v" E' m$ |# limport os+ a9 _$ i4 X+ n
( q" O% b( ]1 f. g5 I) y; @import string1 U; B) |* ^ G9 ]0 F- E
. ~$ V4 R9 }! ~! f/ _
6 t; c9 F) U' n6 d4 M0 Y# c0 L2 Z T6 L0 t, S! n" x% a
def replace(file, search_for, replace_with):% F# `. d# ~2 D" l' }9 X
! \) g3 t) ^0 \. o
# replace strings in a text file6 D& ^8 r' x. j* D% R% L+ r
& T# D6 g. v' q$ g' z4 b; E; C ! e" d9 b5 e/ x% }! r
/ G% l. m" [% H: b+ E
back = os.path.splitext(file)[0] + ".bak" 5 b5 D2 b$ \2 q! K, O j5 l' I y$ B) r+ `* D% J6 Z. g }
temp = os.path.splitext(file)[0] + ".tmp"2 K! B* _" Z! t: M( M
$ V7 N5 M3 K* F/ ~+ a. q2 T
; F* I2 Y; p7 f. u* F4 i/ i. ~: |2 d2 O/ ?5 E
try: ; v( s& |8 O, V 4 T, c% q1 n: h- A8 I/ S2 c+ e# remove old temp file, if any0 J( e# e$ F. I1 G" z, O
; p+ e- O9 M4 R4 L F) Nos.remove(temp) / v% ~ Q F' y ~) G" _/ I6 A : |; [2 B- }* x/ Cexcept os.error: & [7 e1 ^6 m7 G9 Q, \; \- O5 l3 h5 w6 x! g# N
pass & T6 ?. v/ f) }* `& L3 @ / K9 i% |5 s7 ?* @) I7 } A7 z + w9 R3 `& R, Z
# p0 t5 Q$ g' M& B, W
fi = open(file) #7 a# a, T8 f1 W- c E) {5 {, a
. l/ L3 t0 E1 X; t& Q3 z& d
fo = open(temp, "w") ## ~) t5 Y( |6 W, m F' N
* H& S% M, T7 |" V! \
, W9 b% d" X% D9 i5 w/ O9 Y9 _7 I" O8 }5 R: o
for s in fi.readlines():9 r' O# @7 ^, P' G# h
; c! k1 O* s/ Ffo.write(string.replace(s, search_for, replace_with)); l5 ]) N) f0 @! w1 C; y
* y, \1 [* u# a( b# w* U
3 ~% g9 H9 g& z& l1 p8 S, P
% n, H. g2 t* P; r6 s8 @* ` ?
fi.close() # z/ g8 U2 z; Q& }8 X" |* E1 C) t$ q# P
fo.close()/ M8 A, O( e( z' {2 P
6 H. Z$ s4 P0 {; Y/ Bst = os.fstat(fp.fileno()) & t& U) u( l* f: v j8 h1 Y4 [5 E 6 u# \5 U' w* ]# Nprint "fstat", file& r- v( D2 h* j% ~
$ W. B1 `, V% u$ l: f6 }7 } I
dump(st) 6 w( [* `- x. [5 C% F7 U. y# l6 F' k3 e' Z
y1 R: h3 \7 {- x7 |1 O6 E9 w
( q5 O( p: t' o9 W# A+ h" J6 Q
remark: os.stat(path/file)返回文件的对应属性值st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user id of owner), st_gid (group id of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):% D& h m. F/ g P, O& U
& ?. `" n# Q7 }# o
os.fstat(path/file)8 E: u' R$ l$ N( z8 A
! K0 a' y! b8 P. h. A/ x
Return status for file descriptor fd, like stat().