Python文件目录操作

2018-04-16  本文已影响0人  A04

读取当前目录:os.getcwd

>>> os.getcwd()
'D:\Python3.4.4'
>>> 

更改当前目录:os.chdir

>>> os.chdir('c:')
>>> os.getcwd()
'C:\\'
>>>

读取当前目录文件和文件夹:os.listdir(os.getcwd())

>>> os.listdir(os.getcwd())
['Documents and Settings', 'Program Files', 'Program Files (x86)',  'Users', 'Windows']
>>> 

新建文件夹:os.mkdir

>>> os.mkdir('test')
>>>

判断一个目录是否存在:os.path.exists

>>> os.path.exists('c:/test/1')
False
>>> os.mkdir('1')
>>> os.path.exists('c:/test/1')
True
>>> 

判断是文件还是目录:os.path.isdir,os.path.isfile

>>> os.path.isdir('1')
True
>>> os.path.isfile('1')
False
>>> 

文件和文件夹重命名:os.rename

>>> os.listdir(os.getcwd())
['1']
>>> os.rename('1','2')
>>> os.listdir(os.getcwd())
['2']
>>> 
上一篇下一篇

猜你喜欢

热点阅读