1.python的文件讀法在windows和Linux/os X上不一樣,一個(gè)是backslash礁叔,一個(gè)是forward flash,為了統(tǒng)一迄薄,使用os.path.join()
import os
os.path.join(‘usr’,’bin’,’spam’)
2.修改文件路徑琅关;the current working directory
cwd文件夾
任何不是根目錄里的文件都可以假設(shè)在pwd文件夾中,用os.getcwd()獲取文件路徑讥蔽。同時(shí)也可以用os.chdir()更換文件路徑涣易;
import os
os.getcwd()
'C:\\Python34'
os.chdir('C:\\Windows\\System32')
os.getcwd()
'C:\\Windows\\System32'
3.創(chuàng)建文件
import os
os.makedirs('C:\\delicious\\walnut\\waffles')
4.相對(duì)路徑絕對(duì)路徑
#查看文件的絕對(duì)路徑
os.path.abspath(path)
os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
#確定()內(nèi)內(nèi)容是否是絕對(duì)路徑
os.path.isabs('.')
False
os.path.isabs(os.path.abspath('.'))
True
#查看一個(gè)文件對(duì)于另一個(gè)文件的相對(duì)路徑
os.path.relpath(‘文件名’‘待比較文件名’)
>>> os.path.relpath('C:\\Windows', 'C:\\')
'Windows'
>>> os.path.relpath('C:\\Windows', 'C:\\spam\\eggs')
'..\\..\\Windows'
>>> os.getcwd() 'C:\\Python34'
5.基礎(chǔ)名字和文件名
path = 'C:\\Windows\\System32\\calc.exe'
os.path.basename(path)
'calc.exe'
os.path.dirname(path)
'C:\\Windows\\System32'
如果希望將文件的dirname, basename放在同一個(gè)字符串里:
>>> calc = 'C:\\Windows\\System32\\calc.exe'
>>> os.path.split(calc)
('C:\\Windows\\System32', 'calc.exe')
等同于
(os.path.dirname(calc), os.path.basename(calc))
所以split是個(gè)縮略詞,所以比較好冶伞。
如果想將路徑全部拆開(kāi)新症,可以使用
>>>calc.split(os.path.sep)
['C:', 'Windows', 'System32', 'calc.exe']
如果是Linux和OS X的路徑
則根目錄會(huì)用空白表示,例如
>>>'/usr/bin'.split(os.path.sep)
['', 'usr', 'bin']
查看文件大小和文件目錄
查看文件大邢烨荨:os.path.getsize('/user/rachel/calc.exe')
查看文件目錄(注意使用該函數(shù)是在os下徒爹,而不是os.path下):os.listdir('/user/user/rachel')
注意:getsize()只能獲得一個(gè)文件的大小,如果想獲得一個(gè)文件夾的大小芋类,可以將os.path.getsize()和os.listdir()和os.path.join()一起用隆嗅。
>>> totalSize = 0
>>> for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
>>> print(totalSize)
1117846456
1.驗(yàn)證路徑是否正確,2.是否是一個(gè)文件侯繁,3胖喳,是否是文件夾
os.path.isdir()#是否為文件夾
os.path.isfile()#是否為文件
os.path.exists()#是否存在
文件的打開(kāi),閱讀贮竟,書(shū)寫(xiě)
文件打開(kāi):
#如果是windows
>>> helloFile = open('C:\\Users\\your_home_folder\\hello.txt')
#如果是os X
>>> helloFile = open('/Users/your_home_folder/hello.txt')
文件閱讀:
helloContent = helloFile.read()
print helloContent
文件閱讀且保留file中跨行的格式:
例如hello.txt存在很多行
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate,
sonnetFile = open('sonnet29.txt')
sonnetFile.readlines()
[When, in disgrace with fortune and men's eyes,\n', ' I all alone beweep my
outcast state,\n', And trouble deaf heaven with my bootless cries,\n', And
look upon myself and curse my fate,']