6 ~ ]2 p8 o5 x# remove the file4 L! ?2 P" d R' H# R
! ~9 r8 X( r7 z
os.remove("c:\\test\\multiple\\levels\\file.txt") R8 k6 d2 d3 s% Z% L4 S
0 ~& a% m9 x& r9 d' e# and all empty directories above it 2 l. e) e$ S1 E n9 l" V 4 v1 N& Q1 u! l/ c4 ?os.removedirs("c:\\test\\multiple\\levels")+ Z! M; I% Y% T3 w, t; S* D" G9 r
( |& c+ [" z; d 7 k6 o1 ~! Q g; F- }! C 2 z% U9 t, s7 s& f8 L) Vmkdir 和 rmdir只能处理单级目录操作. 6 n4 b7 T, q/ T2 K3 E7 M0 U, [6 g9 p& W! v
若要删除非空目录, 可使用 shutil模块中的rmtree函数7 W. z( S3 N6 p7 m- c: C
1 P# y& m' u/ C9 Q
" Y* G' ]/ _" E/ ~0 X8 V+ W% {1 [4 S* x8 v/ U0 f: ? J9 Y
3. 文件属性的操作+ W( u/ f& v' w4 W9 ^& m0 ?
3 G# J$ V" w/ m7 L6 m2 ]! b
import os / `: @& N* P3 {3 ]; D6 l S& H% z L
import time% v. x+ r; H# x9 X
9 g r6 p% [' N3 ]! z5 @- }% Z' _
file = 'c:\qtest\editor.pyc' + i0 D: ]9 V% d' W; N( e) H 1 {2 S' c' F5 u) } * e3 S" D. ]/ |
6 G7 @: A8 ?& k1 m
st = os.stat(file) . z5 @5 V; e6 f% \( q, ?1 E- G7 q+ Y$ Z! {$ A/ l! S: ~* E
print "state", file 2 _- I" g6 }- M' U6 ]% I1 Q) f * q% v S t+ I4 T8 ^' p6 v+ V 4 v+ N- Q; P# E* p7 |
: E$ C. g1 I8 |5 B2 J
def dump(st):8 |- D7 o# r& V7 b6 v& }- U
; K* t! B9 ?' n& d }print "- created:", time.ctime(ctime)& x: ]+ k: ]; r% ]! y5 R
G s( l [- Dprint "- last accessed:", time.ctime(atime) q3 z) h% j+ u! X/ ?+ T
+ G8 u8 }9 f! ~! z9 l) G% P9 Eprint "- last modified:", time.ctime(mtime)8 ]7 q$ j9 F' G' W* i& N
6 ?, y; h9 \( o" @print "- mode:", oct(mode) 8 s+ V! |: ^, ?/ T- s8 r( V; X4 k6 B, v F0 e) Y+ I t
print "- inode/dev:", ino, dev' n, E4 i3 z% ?3 O$ A5 [
0 C. R9 x E/ c/ Z; k6 l$ c* g
- i- S: _9 ]( e) `/ Y
I, _8 m- Y4 e, ]. a3 ?1 ?( Z' Y
print dir(st), \& h& p- \6 E, _" S0 s
: c! |: W8 V% L* P& E% ^print 8 r& }8 J0 x/ `/ @* G7 S# w! A3 t/ y: i. R% o5 u, B
dump(st)9 b7 \ z7 s3 h7 r; J6 B2 Y
; p' M9 k- g+ r Y# print1 `1 k5 U) U6 u! x7 ]- h7 _8 u
$ J9 N1 h0 e- f0 r6 j6 I0 H. J9 n& ~ @
- d! {$ f$ a5 k! c " V% ~% s( Y" [3 k! ^fp = open(file) ; m2 _, ^6 I* p6 ]- [9 m% o( o* u2 ?0 h* \0 }1 k v
st = os.fstat(fp.fileno()) , [% k ~$ Q, x 6 O& I* I, [, j6 Sprint "fstat", file & M: J+ A! z1 B- F& w; I) c7 r0 U0 Q: j' y, y$ I4 \6 N
dump(st) / ]2 f" n4 Q) @+ X' Z" x+ ~2 }# ^4 I7 s0 Z$ i: d: r
$ \+ P) U, T% w* U# c [
% d! M7 A3 q9 o. v1 S
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):! o; F9 q q# J/ z
8 k1 c/ o; H' ^. X e
os.fstat(path/file)( }7 n& K+ N" y! d$ P" H
" Q8 O) c& X8 S; gReturn status for file descriptor fd, like stat().