Python os模塊詳解

轉載自:http://www.reibang.com/p/e294d124a076

操作文件

# I use jupyter notebook to create some file
!touch foo.txt
!echo Hello > foo.txt
!cat foo.txt

Hello

# rename file
os.rename('foo.txt','bar.txt')
!cat bar.txt

Hello

# remove file
os.remove('bar.txt')

改變目錄

# current dir
print os.getcwd() # current working directory

/Users/yongle/OMOOC2py/cheat

# go down
os.chdir('img')
print os.getcwd()

# go back up
os.chdir(os.pardir) #or simply os.chdir('..')
print os.getcwd()

/Users/yongle/OMOOC2py/cheat/img
/Users/yongle/OMOOC2py/cheat

遍歷目錄listdir

# listdir
!touch a.txt b.txt
for file in os.listdir('.'):
    # os.listdir() return a list
    if file.endswith('.txt'):
        print file

a.txt
b.txt

遍歷os.walk

os.chdir('doc')
# Directory tree generator.
# For each dir in the dir tree rooted at top (including top
# itself, but excluding '.' and '..'), yields a 3-tuple
# dirpath, dirnames, filenames
for dirpath, dirnames, filenames in os.walk('.'):
    print dirnames
    print filenames
    break # only one level needed, or just use listdir

['folder1', 'folder2']
['.DS_Store', 'a.txt', 'b.txt']

增刪目錄

單層目錄

# make a dir, one level, no duplication allowed
os.mkdir('test')
# remove a dir, one level, not empty will raise OSError
os.rmdir('test')

多層目錄

# make dirs, multipul level
os.makedirs('test/mulitiple/levels')
# remove all empty directories above it, ensure empty
os.removedirs('test/mulitiple/levels')

非空目錄

# remove non empty dir, ust a new module shutil.rmtree
# copy function is also useful
import shutil
# copy a.txt to backup folder
# or just shutil.copy('a.txt','backup/')
# use shutil.copytree to copy a folder like cp -r
os.mkdir('backup')
shutil.copy('a.txt',os.path.join('backup','a_backup.txt'))
# remove non empty folder
shutil.rmtree('backup/')

os.path模塊

# is a dir or not
print(os.path.isdir('img'))
print(os.path.isdir('a.txt'))

True
False

# is a file or not
print(os.path.isfile('img'))
print(os.path.isfile('a.txt'))

False
True

# determine the presence of path(a file or dir); os.path.lexists?
print(os.path.exists('img'))
print(os.path.exists('a.txt'))
print(os.path.exists('none_exist.txt'))

True
True
False

# Join two or more pathname components, inserting '/' as needed.
# If any component is an absolute path, all previous path components will be discarded.
print(os.path.join('/Users','john'))
print(os.path.join('/Users','/john'))
print(os.path.join('/Users','john','a.txt'))

/Users/john
/john
/Users/john/a.txt

# split a pathname. Returns "(head, tail)" 
# where "tail" is everything after the final slash.
os.path.split('/Users/john/a.txt')

('/Users/john', 'a.txt')

# split the extension from a pathname
os.path.splitext('/Users/john/a.txt')

('/Users/john/a', '.txt')

# determine the size of a path(file or dir)
os.path.getsize('a.txt')

0

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末伦仍,一起剝皮案震驚了整個濱河市脐区,隨后出現的幾起案子丑孩,更是在濱河造成了極大的恐慌偏螺,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件围小,死亡現場離奇詭異浙值,居然都是意外死亡,警方通過查閱死者的電腦和手機望忆,發(fā)現死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來竿秆,“玉大人启摄,你說我怎么就攤上這事∮母郑” “怎么了歉备?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長匪燕。 經常有香客問我蕾羊,道長,這世上最難降的妖魔是什么帽驯? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任龟再,我火速辦了婚禮,結果婚禮上尼变,老公的妹妹穿的比我還像新娘利凑。我一直安慰自己,他們只是感情好嫌术,可當我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布哀澈。 她就那樣靜靜地躺著,像睡著了一般蛉威。 火紅的嫁衣襯著肌膚如雪日丹。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天蚯嫌,我揣著相機與錄音哲虾,去河邊找鬼。 笑死择示,一個胖子當著我的面吹牛束凑,可吹牛的內容都是我干的。 我是一名探鬼主播栅盲,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼汪诉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了谈秫?” 一聲冷哼從身側響起扒寄,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎拟烫,沒想到半個月后该编,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡硕淑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年课竣,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片置媳。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡于樟,死狀恐怖,靈堂內的尸體忽然破棺而出拇囊,到底是詐尸還是另有隱情迂曲,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布寥袭,位于F島的核電站奢米,受9級特大地震影響,放射性物質發(fā)生泄漏纠永。R本人自食惡果不足惜鬓长,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望尝江。 院中可真熱鬧涉波,春花似錦、人聲如沸炭序。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽惭聂。三九已至窗声,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間辜纲,已是汗流浹背笨觅。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工拦耐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人见剩。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓杀糯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親苍苞。 傳聞我的和親對象是個殘疾皇子固翰,可洞房花燭夜當晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內容