- 1.文件路徑
- 1.1 不同系統(tǒng)環(huán)境下的路徑
- 1.2 當(dāng)前工作目錄
- 1.3 絕對路徑和相對路徑
- 1.4 新建文件夾—— os.makedirs()
- 2.文件的讀寫
- 2.1 打開文件
- 2.2 讀寫文件
- 3.文件的操作
- 3.1 shutil模塊簡介
- 3.2 刪除文件
- 3.3 遍歷目錄樹 os.walk(dir)
- 3.4 zipfile模塊——操作壓縮文件
1. 文件路徑
1.1 不同系統(tǒng)環(huán)境下的路徑
不同系統(tǒng)的文件分隔符可能會不同,Window下,使用""作為文件分隔符,OS 和Linux下使用"/",在處理文件的時候,必須處理這中情況。
- 使用os.path.sep 來獲取文件分隔符
- 使用os.path.join()來獲取路徑。
得到:import os path = os.path.join("dir1", "dir2", "dir3", "file1") print path path2 = os.path.join("user/bin/python", "newFile") print path2
dir1/dir2/dir3/file1
user/bin/python/newFile
1.2 當(dāng)前工作目錄
每個運行在計算機上的程序,都有一個“當(dāng)前工作目錄”,或cwd。所有沒有從根文件夾開始的文件名或路徑,都假定在當(dāng)前工作目錄下。利用os.getcwd()函數(shù),可以取得當(dāng)前工作路徑的字符串,并可以利用os.chdir()改變它。
>>> import os
>>> os.getcwd()
'/Users/chelsea/Documents/workspace/test/src/mcx/basePython'
>>> os.chdir('/Users/chelsea/Documents/workspace/test/src/mcx/test')
>>> os.getcwd()
'/Users/chelsea/Documents/workspace/test/src/mcx/test'
os.chdir(newPath) newPath必須是已存在的路徑,否則會拋出異常:OSError: [Errno 2] No such file or directory
1.3 絕對路徑和相對路徑
- 絕對路徑:從根文件夾開始
- 相對路徑:相對于當(dāng)前工作目錄開始
- (.)、(..) 文件夾:不是真正的文件夾,(.)表示該目錄的縮寫,(..) 表示符文件夾。如,當(dāng)前目錄'/Users/chelsea/Documents/workspace/test/src/mcx/basePython', 目錄下有test.py文件,則可以表示為.\test.py; "..\test"表示文件夾'/Users/chelsea/Documents/workspace/test/src/mcx/test'。
1.4 新建文件夾—— os.makedirs()
import os
os.makedirs('/Users/chelsea/Documents/workspace/test/src/mcx/newfolder')
os.path模塊常用方法
- os.path.abspath(path) 回參數(shù)的絕對路徑的字符串。
- os.path.isabs(path),是否是一個絕對路徑。
- os.path.relpath(path,start) 返回相對start的相對路徑的字符串。如果沒有提供start,就使用當(dāng)前工作目錄作為開始路徑。
- os.path.dirname(path) 返回路徑字符串(最后一個/前的文字)。
- os.path.basename(path) 返回文件名(最后一個/后的文字)。
- os.path.split(calcFilePath) 獲取路徑和文件名,返回一個元組,元組有兩個值,第一個值為路徑,第二個值為文件名。
- os.path.getsize(path) 獲取文件大小。
- os.path.exists(path) 文件是否存在。
- os.path.isfile(path) 是否是文件
- os.path.isdir(path) 是否是文件夾
- os.listdir(path) 獲取 path下的文件列表。返回一個列表,值為文件名。
2. 文件的讀寫
在Python中,讀寫文件有3個步驟:
- 調(diào)用open()函數(shù),返回一個File對象。
- 調(diào)用File對象的read()或write()方法。
- 調(diào)用File對象的close()方法,關(guān)閉該文件。
2.1 打開文件
- open(path) 以只讀的方式打開文件,若文件不存在拋出異常:IOError: [Errno 2] No such file or directory。不可以寫入數(shù)據(jù)。
- open(path, "r") 同上。
- open(path, "w") 以只寫的方式打開文件,若文件則創(chuàng)建文件。讀數(shù)據(jù)拋出異常:IOError: File not open for reading
| mode char | 含義 |
|---|---|
| 'r' | open for reading (default) |
| 'w' | open for writing, truncating the file first |
| 'x' | open for exclusive creation, failing if the file already exists |
| 'a' | open for writing, appending to the end of the file if it exists |
| 'b' | binary mode |
| 't' | text mode (default) |
| '+' | open a disk file for updating (reading and writing) |
| 'U' | universal newlines mode (deprecated) |
path = '/Users/chelsea/Documents/workspace/test/test.txt';
file = open(path)
2.2 讀寫文件
- file.read() 將文件內(nèi)容看成是單個大字符串,改方法返回這個字符串。
- file.readlines() 返回一個列表,列表的每個元素是文件的每一行。
- file.write(content)
shelve模塊保存變量
shelve模塊可以將程序中的變量保存到數(shù)據(jù)庫中。
- 保存數(shù)據(jù):
import shelve # 將會在運行目錄下產(chǎn)生一個mcxconfig.db configFile = shelve.open('mcxConfig') configFile['name'] = 'machenxi' configFile.close() - 讀取數(shù)據(jù)
import shelve configFile = shelve.open('mcxConfig') print configFile['name']
pprint.pformat()保存變量
import 語句導(dǎo)入的模塊本身也是Python腳本,可以使用pprint.pformat()來保存一個Python腳本,以便在其他Python程序中使用。
寫入:
import pprint
cats=[{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
pprint.pformat(cats)
fileObj=open('myCats.py','w')
fileObj.write('cats='+pprint.pformat(cats)+'\n')
fileObj.close()
讀?。?/p>
import myCats
priny(myCats.cats)
運行結(jié)果: [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
3. 文件的操作
3.1 shutil模塊簡介
使用shutil模塊,可以對文件進行復(fù)制、移動、改名、刪除。
- shutil.copy(source, destination) 將路徑source處的文件復(fù)制到路徑destination處的文件夾,返回新的路徑。(復(fù)制單個文件)
- shutil.copyTree(source, destination) 復(fù)制整個文件夾,返回新的路徑。
- shutil.move(source, destination) 移動文件夾,返回新的路徑,有重名文件,舊文件會被覆蓋。destination可以是一個文件路徑,移動后文件將被重命名;destination是文件夾路徑時必須存在,否則會異常。
3.2 刪除文件
3.2.1 永久刪除文件
- os.unlink(path) 刪除path處文件。
- os.rmdir(path) 刪除path處的文件夾,文件夾必須為空。
- shutil.rmtree(path) 刪除path文件,包含的文件夾和文件都會被刪除。
3.2.2 send2trash模塊——把文件放到回收站
import send2trash
send2trash.send2trash(path)
3.3 遍歷目錄樹 os.walk(dir)
os.walk(dir) os.walk()函數(shù)可以用于for循環(huán)語句,遍歷目錄樹,就像使用range()函數(shù)遍歷一個范圍的數(shù)字一樣。
os.walk()在循環(huán)的每次迭代中,返回3個值:
1.當(dāng)前文件夾名稱的字符串。(是指for循環(huán)當(dāng)前迭代的文件夾)
2.當(dāng)前文件夾中子文件夾的字符串的列表。
3.當(dāng)前文件夾中文件的字符串的列表。
程序的當(dāng)前工作目錄,不會因為os.walk()而改變。
import os
for folderName, subfolders, filenames in os. walk(' C:\\ delicious'):
print(' The current folder is ' + folderName)
for subfolder in subfolders:
print(' SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print(' FILE INSIDE ' + folderName + ': '+ filename) print('')
3.4 zipfile模塊——操作壓縮文件
3.4.1 讀取ZIP文件
import zipfile, os
exampleZip = zipfile.ZipFile('example.zip')
exampleZip.namelist() # 獲取所有文件夾以及文件夾下的字符串列表 ['spam.txt', 'cats/', 'cats/catnames. txt', 'cats/zophie.jpg']
spamInfo = exampleZip. getinfo(' spam. txt')
spamInfo.file_ size # 獲取文件實際大小
spamInfo.compress_size # 獲取文件壓縮后的大小
exampleZip. close()
3.4.3 解壓縮ZIP文件
import zipfile, os
exampleZip = zipfile.ZipFile('example.zip') # 解壓到當(dāng)前工作目錄
exampleZip = zipfile.ZipFile('example.zip', destinationPath) # 解壓到指定目錄
exampleZip.extractall()
exampleZip. close()
3.4.3 壓縮ZIP文件
import zipfile
newZip = zipfile. ZipFile('new.zip', 'w') # 'w'模式會覆蓋new.zip文件里的內(nèi)容,若要內(nèi)new.zip中添加一個文件,使用'a'。
newZip.write('spam.txt', compress_type= zipfile.ZIP_ DEFLATED)
newZip.close()