P- ^6 Y$ U2 N" D 5 m- b" Z5 z& _: n9 _7 }% S( ?os 模块提供了一个统一的操作系统接口函数, 这些接口函数通常是平台指定的,os 模块能在不同操作系统平台如 nt 或 posix中的特定函数间自动切换,从而能实现跨平台操作' y5 r: @4 x' K& o# h
' E0 Y' f; B; H u4 d3 o% w) C
3 d- F" e, v* S! N
/ `% p8 r5 r) ]' }) C+ i1.文件操作8 [* L2 o8 Y. R
0 B2 C3 O! r3 Z4 @& y8 p( g
build-in函数 open 实现文件创建, 打开, 修改文件的操作 ) H: a, l% T" M% B ) v% ~" Y4 S. o. J3 ?: ~ ! V5 B A+ _# J, p7 N' {9 d
- Y! q8 q3 [6 k4 l% i' Wimport os 1 j! P+ F$ J; m3 o& s5 h * f* w& d/ ^1 T" j4 k. ?) Ximport string2 M# t- _% G4 z: ?7 o
# g- J" V- i1 u$ y$ i; s, s + _4 S; R9 o. x
& _1 s& z! }& D+ g5 l! H, Z
def replace(file, search_for, replace_with):6 [: U7 k3 u. W
; s9 W7 ]& h- a7 N4 V) t. z) p
# replace strings in a text file : z Q" ^( q! y/ l) H5 |: a) a$ Q7 w ( s H5 E, }* y , I j9 z) N! _$ o # u1 S. @ Z; C: Bback = os.path.splitext(file)[0] + ".bak"5 X, ~+ ~; X+ T# ?$ D0 D
1 ^& \" q; T% J' t- E }( K
temp = os.path.splitext(file)[0] + ".tmp") U4 O4 ], [. U( F' {8 x7 @
; v! C, E0 r( z+ T0 H- u6 e
8 C* r8 y6 v4 _! o! X! \0 ^
, u& t _' c: T8 i1 s, Rtry:( `% }8 R$ q5 J. p
, t1 |8 H" e* C) W' l: u, p
# remove old temp file, if any . a; l. D3 @: T& d! k * W2 N! v9 \ } j: p3 @1 M! Gos.remove(temp) 0 W- d$ {) k: Q a- E# e' ]9 S% I' P8 O5 u' j, z* m% ]
except os.error:# K) \" v8 B, ~+ ]6 w. G# w
3 s! c/ H5 T6 a+ B: g
pass 7 Q' o7 I+ A2 U; V' J 0 Z' g+ _% @- E ]# g w 1 F/ a) f4 w4 K( w' a, I/ s. b 0 v x6 Q% t% Ufi = open(file) # ( K: e5 K8 h# t9 p7 Y& `: C/ @- i 9 y/ B, y9 [) o/ {# ]fo = open(temp, "w") #! @% w& E+ E7 b k" H
: A/ h5 o/ p3 Z( ] F . h& ^; `. `$ K6 {fp = open(file)8 o, h4 n4 B; m& c5 |' z
: \; A1 \; J2 c/ b# o
st = os.fstat(fp.fileno()) - G& X6 i' W! P 1 l9 b0 }8 ?! n" n+ N6 Pprint "fstat", file0 t& J. U% `& u: F m6 R
0 Q- ` k9 [) w* n* m4 V$ E5 q
dump(st)2 y S5 R/ ]* X6 z5 ]2 r9 w
3 C6 m( y. F' U/ \3 u" t
9 L6 T4 D8 ?" K
% B. ]8 _/ \7 }2 _# J
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): ! B* v4 l3 v# z/ k |" w, _4 O; A( `8 Z: y5 U( k% y
os.fstat(path/file) 3 c. F6 U3 d1 _4 C8 k |! C, E J* W# L9 i
Return status for file descriptor fd, like stat().