跳轉至內容

Python 程式設計/檔案

來自華夏公益教科書,開放書籍,開放世界


檔案 I/O

[編輯 | 編輯原始碼]

讀取整個檔案

inputFileText = open("testit.txt", "r").read()
print(inputFileText)

在這種情況下,“r”引數表示檔案將以只讀模式開啟。

從檔案中讀取一定數量的位元組

inputFileText = open("testit.txt", "r").read(123)
print(inputFileText)

開啟檔案時,從檔案開頭開始讀取。如果想要對檔案進行更隨機的訪問,可以使用 seek() 更改檔案中的當前位置,並使用 tell() 獲取檔案中的當前位置。以下示例對此進行了說明

>>> f=open("/proc/cpuinfo","r")
>>> f.tell()
0L
>>> f.read(10)
'processor\t'
>>> f.read(10)
': 0\nvendor'
>>> f.tell()
20L
>>> f.seek(10)
>>> f.tell()
10L
>>> f.read(10)
': 0\nvendor'
>>> f.close()
>>> f
<closed file '/proc/cpuinfo', mode 'r' at 0xb7d79770>

這裡,一個檔案被開啟,兩次讀取十個位元組,tell() 顯示當前偏移量位於位置 20,現在 seek() 被用來回到位置 10(第二次讀取開始的位置),十個位元組被再次讀取並列印。當不再需要對檔案進行操作時,使用 close() 函式關閉我們開啟的檔案。

一次讀取一行

for line in open("testit.txt", "r"):
    print(line)

在這種情況下,readlines() 將返回一個數組,該陣列包含檔案中的各個行作為陣列條目。可以使用 readline() 函式讀取單行,該函式將當前行作為字串返回。此示例將在檔案的各個行之間輸出一個額外的換行符,這是因為從檔案中讀取了一個換行符,而 print 引入了另一個換行符。

寫入檔案需要 open() 的第二個引數為“w”,這將覆蓋檔案已存在時開啟檔案時檔案的現有內容

outputFileText = "Here's some text to save in a file"
open("testit.txt", "w").write(outputFileText)

追加到檔案需要 open() 的第二個引數為“a”(來自追加)

outputFileText = "Here's some text to add to the existing file."
open("testit.txt", "a").write(outputFileText)

請注意,這不會在現有檔案內容和要新增的字串之間新增換行符。

從 Python 2.5 開始,可以使用 with 關鍵字來確保檔案控制代碼儘快被釋放,並使其異常安全

with open("input.txt") as file1:
  data = file1.read()
  # process the data

或者一次一行

with open("input.txt") as file1:
  for line in file1:
    print(line)

with 關鍵字相關的是 上下文管理器 章節。

連結

測試檔案

[編輯 | 編輯原始碼]

確定路徑是否存在

import os
os.path.exists('<path string>')

在 Microsoft Windows™ 等系統上工作時,目錄分隔符將與路徑字串發生衝突。為了解決這個問題,請執行以下操作

import os
os.path.exists('C:\\windows\\example\\path')

但是,更好的方法是使用“原始”或 r

import os
os.path.exists(r'C:\windows\example\path')

os.path 中有一些其他方便的函式,其中 os.path.exists() 僅確認路徑是否存在,而其他函式可以讓你知道路徑是檔案、目錄、掛載點還是符號連結。甚至還有一個函式 os.path.realpath() 可以顯示符號連結的真實目標

>>> import os
>>> os.path.isfile("/")
False
>>> os.path.isfile("/proc/cpuinfo")
True
>>> os.path.isdir("/")
True
>>> os.path.isdir("/proc/cpuinfo")
False
>>> os.path.ismount("/")
True
>>> os.path.islink("/")
False
>>> os.path.islink("/vmlinuz")
True
>>> os.path.realpath("/vmlinuz")
'/boot/vmlinuz-2.6.24-21-generic'

常見檔案操作

[編輯 | 編輯原始碼]

要複製或移動檔案,請使用 shutil 庫。

import shutil
shutil.move("originallocation.txt","newlocation.txt")
shutil.copy("original.txt","copy.txt")

要執行遞迴複製,可以使用 copytree(),要執行遞迴刪除,可以使用 rmtree()

import shutil
shutil.copytree("dir1","dir2")
shutil.rmtree("dir1")

要刪除單個檔案,os 模組中存在 remove() 函式

import os
os.remove("file.txt")

查詢檔案

[編輯 | 編輯原始碼]

可以使用 glob 查詢檔案

glob.glob('*.txt') # Finds files in the current directory ending in dot txt 
glob.glob('*\\*.txt') # Finds files in any of the direct subdirectories
                      # of the currect directory ending in dot txt 
glob.glob('C:\\Windows\\*.exe')
for fileName in glob.glob('C:\\Windows\\*.exe'):
  print(fileName)
glob.glob('C:\\Windows\\**.exe', recursive=True) # Py 3.5: ** allows recursive nesting

可以使用 listdir 列出目錄的內容

filesAndDirectories=os.listdir('.')
for item in filesAndDirectories:
  if os.path.isfile(item) and item.endswith('.txt'):
    print("Text file: " + item)
  if os.path.isdir(item):
    print("Directory: " + item)

獲取目錄中所有專案的列表,包括巢狀的專案

for root, directories, files in os.walk('/user/Joe Hoe'):
  print("Root: " + root)                         # e.g. /user/Joe Hoe/Docs
  for dir1 in directories:
    print("Dir.: " + dir1)                       # e.g. Fin
    print("Dir. 2: " + os.path.join(root, dir1)) # e.g. /user/Joe Hoe/Docs/Fin
  for file1 in files:
    print("File: " + file1)                      # e.g. MyFile.txt
    print("File 2: " + os.path.join(root, file1))# e.g. /user/Joe Hoe/Docs/MyFile.txt

上面,root 採用 /user/Joe Hoe 中每個目錄的值,包括 /user/Joe Hoe 本身,而目錄和檔案僅是每個 root 中直接存在的那些。

獲取目錄中所有以 .txt 結尾的檔案列表,包括巢狀的專案,使用列表推導

files = [os.path.join(r, f) for r, d, fs in os.walk(".") for f in fs
         if f.endswith(".txt")]
# As iterator
files = (os.path.join(r, f) for r, d, fs in os.walk(".") for f in fs
         if f.endswith(".txt"))

連結

當前目錄

[編輯 | 編輯原始碼]

獲取當前工作目錄

os.getcwd()

更改當前工作目錄

os.chdir('C:\\')
[編輯 | 編輯原始碼]
華夏公益教科書