溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中最常見的文件操作技巧有哪些

發布時間:2021-10-28 11:45:58 來源:億速云 閱讀:181 作者:iii 欄目:編程語言

本篇內容介紹了“Python中最常見的文件操作技巧有哪些”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

打開&關閉文件

讀取或寫入文件前,首先要做的就是打開文件,Python的內置函數open可以打開文件并返回文件對象。文件對象的類型取決于打開文件的模式,可以是文本文件對象,也可以是原始二進制文件,或是緩沖二進制文件對象。每個文件對象都有諸如 read()和write()之類的方法。

你能看出以下代碼塊中存在的問題嗎?我們稍后來揭曉答案。

file = open("test_file.txt","w+")  file.read()  file.write("a new line")

Python文檔列出了所有可能的文件模式,其中最常見的模式可見下表。但要注意一個重要規則,即:如果某一文件存在,那么任何與w相關的模式都會截斷該文件,并再創建一個新文件。如果你不想覆蓋原文件,請謹慎使用此模式,或盡量使用追加模式 a。

Python中最常見的文件操作技巧有哪些

上一個代碼塊中的問題是打開文件后未關閉。在處理文件后關閉文件很重要,因為打開的文件對象可能會出現諸如資源泄漏等不可預測的風險,以下兩種方式可以確保正確關閉文件。

1.使用 close()

第一種方法是顯式使用close()。但較好的做法是將該代碼放在最后,因為這樣的話就可以確保在任何情況下都能關閉該文件,而且會使代碼更加清晰。但開發人員也應負起責任,記得關閉文件。

try:      file =open("test_file.txt","w+")      file.write("a new line")  exception Exception as e:      logging.exception(e)  finally:      file.close()

2.使用上下文管理器,with open(...) as f

第二種方法是使用上下文管理器。若你對此不太熟悉,還請查閱Dan Bader用Python編寫的上下文管理器和“ with”語句。用withopen() as f實現了使用__enter__ 和 __exit__ 方法來打開和關閉文件。此外,它將try / finally語句封裝在上下文管理器中,這樣我們就不會忘記關閉文件啦。

with open("test_file","w+") as file:      file.write("a new line")

兩種方法哪個更優?這要看你使用的場景。以下示例實現了將50000條記錄寫入文件的3種不同方式。從輸出中可見,use_context_manager_2()函數與其他函數相比性能極低。這是因為with語句在一個單獨函數中,基本上會為每條記錄打開和關閉文件,這種繁瑣的I / O操作會極大地影響性能。

def _write_to_file(file, line):      with open(file, "a") as f:          f.write(line)  def _valid_records():      for i inrange(100000):          if i %2==0:              yield i  def use_context_manager_2(file):      for line in_valid_records():          _write_to_file(file, str(line))  def use_context_manager_1(file):      with open(file, "a") as f:          for line in_valid_records():              f.write(str(line))  def use_close_method(file):      f =open(file, "a")      for line in_valid_records():          f.write(str(line))      f.close()  use_close_method("test.txt")  use_context_manager_1("test.txt")  use_context_manager_2("test.txt")  # Finished use_close_method  in 0.0253 secs  # Finished  use_context_manager_1 in 0.0231 secs  # Finished use_context_manager_2  in 4.6302 secs

對比close()和with語句兩種方法

讀寫文件

文件打開后,開始讀取或寫入文件。文件對象提供了三種讀取文件的方法,分別是 read()、readline() 和readlines()。

  •  默認情況下,read(size=-1)返回文件的全部內容。但若文件大于內存,則可選參數 size 能幫助限制返回的字符(文本模式)或字節(二進制模式)的大小。 

  •  readline(size=-1) 返回整行,最后包括字符 n。如果 size 大于0,它將從該行返回最大字符數。 

  •  readlines(hint=-1) 返回列表中文件的所有行。若返回的字符數超過了可選參數hint,則將不返回任何行。 

在以上三種方法中,由于read() 和readlines()在默認情況下以字符串或列表形式返回完整的文件,所以這兩種方法的內存效率較低。一種更有效的內存迭代方式是使用readline()并使其停止讀取,直到返回空字符串??兆址啊北硎局羔樀竭_文件末尾。

with open( test.txt ,  r ) as reader:      line = reader.readline()      while line !="":          line = reader.readline()          print(line)

以節省內存的方式讀取文件

編寫方式有兩種:write()和writelines()。顧名思義,write()能編寫一個字符串,而writelines()可編寫一個字符串列表。開發人員須在末尾添加 n。

with open("test.txt", "w+") as f:      f.write("hi")      f.writelines(["this is aline", "this is another line"])  # >>>cat test.txt  # hi  # this is a line  # this is anotherline

在文件中寫入行

若要將文本寫入特殊的文件類型(例如JSON或csv),則應在文件對象頂部使用Python內置模塊json或csv。

import csv  import json  with open("cities.csv", "w+") as file:      writer = csv.DictWriter(file, fieldnames=["city", "country"])      writer.writeheader()     writer.writerow({"city": "Amsterdam", "country": "Netherlands"})      writer.writerows([                   {"city": "Berlin", "country": "Germany"},                   {"city": "Shanghai", "country": "China"},      ])  # >>> cat cities.csv  # city,country  # Amsterdam,Netherlands  # Berlin,Germany  # Shanghai,China  with open("cities.json", "w+") as file:      json.dump({"city": "Amsterdam", "country": "Netherlands"}, file)  # >>>cat cities.json  # { "city":"Amsterdam", "country": "Netherlands" }

在文件內移動指針

當打開文件時,會得到一個指向特定位置的文件處理程序。在r和w模式下,處理程序指向文件的開頭。在a模式下,處理程序指向文件的末尾。

tell() 和 seek()

當讀取文件時,若沒有移動指針,那么指針將自己移動到下一個開始讀取的位置。以下2種方法可以做到這一點:tell()和seek()。

tell()以文件開頭的字節數/字符數的形式返回指針的當前位置。seek(offset,whence = 0)將處理程序移至遠離wherece的offset字符處。wherece可以是:

  •  0: 從文件開頭開始

  •  1:從當前位置開始

  •  2:從文件末尾開始 

在文本模式下,wherece僅應為0,offset應≥0。

with open("text.txt", "w+") as f:      f.write("0123456789abcdef")      f.seek(9)      print(f.tell()) # 9 (pointermoves to 9, next read starts from 9)      print(f.read()) # 9abcdef

tell()和seek()

了解文件狀態

操作系統中的文件系統具有許多有關文件的實用信息,例如:文件的大小,創建和修改的時間。要在Python中獲取此信息,可以使用os或pathlib模塊。實際上,os和pathlib之間有很多共同之處。但后者更面向對象。

os 

使用os.stat(“ test.txt”)可以獲取文件完整狀態。它能返回具有許多統計信息的結果對象,例如st_size(文件大小,以字節為單位),st_atime(最新訪問的時戳),st_mtime(最新修改的時戳)等。

print(os.stat("text.txt"))  >>> os.stat_result(st_mode=33188, st_ino=8618932538,st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=16,st_atime=1597527409, st_mtime=1597527409, st_ctime=1597527409)

單獨使用os.path可獲取統計信息。

os.path.getatime()  os.path.getctime()  os.path.getmtime()  os.path.getsize()

Pathlib

使用pathlib.Path("text.txt").stat()也可獲取文件完整狀態。它能返回與os.stat()相同的對象。

print(pathlib.Path("text.txt").stat())  >>>os.stat_result(st_mode=33188, st_ino=8618932538, st_dev=16777220, st_nlink=1,st_uid=501, st_gid=20, st_size=16, st_atime=1597528703, st_mtime=1597528703,st_ctime=1597528703)

下文將在諸多方面比較os和pathlib的異同。

復制,移動和刪除文件 

Python有許多處理文件移動的內置模塊。你在信任Google返回的第一個答案之前,應該明白:模塊選擇不同,性能也會不同。有些模塊會阻塞線程,直到文件移動完成;而其他模塊則可能異步執行。

shutil

shutil是用于移動、復制和刪除文件(夾)的最著名的模塊。它有3種僅供復制文件的方法:copy(),copy2()和copyfile()。

copy() v.s. copy2():copy2()與copy()非常相似。但不同之處在于前者還能復制文件的元數據,例如最近的訪問時間和修改時間等。不過由于Python文檔操作系統的限制,即使copy2()也無法復制所有元數據。

shutil.copy("1.csv", "copy.csv")  shutil.copy2("1.csv", "copy2.csv")  print(pathlib.Path("1.csv").stat())  print(pathlib.Path("copy.csv").stat())  print(pathlib.Path("copy2.csv").stat())  # 1.csv  # os.stat_result(st_mode=33152, st_ino=8618884732,st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=11,st_atime=1597570395, st_mtime=1597259421, st_ctime=1597570360) # copy.csv  # os.stat_result(st_mode=33152, st_ino=8618983930,st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=11,st_atime=1597570387, st_mtime=1597570395, st_ctime=1597570395) #copy2.csv  # os.stat_result(st_mode=33152, st_ino=8618983989, st_dev=16777220,st_nlink=1, st_uid=501, st_gid=20, st_size=11, st_atime=1597570395,st_mtime=1597259421, st_ctime=1597570395)

 copy() v.s. copy2()

copy() v.s. copyfile():copy()能將新文件的權限設置為與原文件相同,但是copyfile()不會復制其權限模式。其次,copy()的目標可以是目錄。如果存在同名文件,則將覆蓋原文件或創建新文件。但是,copyfile()的目標必須是目標文件名。

shutil.copy("1.csv", "copy.csv")  shutil.copyfile("1.csv", "copyfile.csv")  print(pathlib.Path("1.csv").stat())  print(pathlib.Path("copy.csv").stat())  print(pathlib.Path("copyfile.csv").stat())  # 1.csv  #os.stat_result(st_mode=33152, st_ino=8618884732, st_dev=16777220, st_nlink=1,st_uid=501, st_gid=20, st_size=11, st_atime=1597570395, st_mtime=1597259421,st_ctime=1597570360) # copy.csv  #os.stat_result(st_mode=33152, st_ino=8618983930, st_dev=16777220, st_nlink=1,st_uid=501, st_gid=20, st_size=11, st_atime=1597570387, st_mtime=1597570395,st_ctime=1597570395) # copyfile.csv  # permission(st_mode) is changed  #os.stat_result(st_mode=33188, st_ino=8618984694, st_dev=16777220, st_nlink=1,st_uid=501, st_gid=20, st_size=11, st_atime=1597570387, st_mtime=1597570395,st_ctime=1597570395) shutil.copyfile("1.csv", "./source") #IsADirectoryError: [Errno 21] Is a directory:  ./source

 copy() v.s. copyfile()

os

os 模塊內含system()函數,可在subshell中執行命令。你需要將該命令作為參數傳遞給system(),這與在操作系統上執行命令效果相同。為了移動和刪除文件,還可以在os模塊中使用專用功能。

# copy  os.system("cp 1.csvcopy.csv")   # rename/move  os.system("mv 1.csvmove.csv")  os.rename("1.csv", "move.csv")  # delete  os.system("rmmove.csv")

異步復制/移動文件

到目前為止,解決方案始終是同步執行的,這意味著如果文件過大,需要更多時間移動,那么程序可能會終止運行。如果要異步執行程序,則可以使用threading,multiprocessing或subprocess模塊,這三個模塊能使文件操作在單獨的線程或進程中運行。

import threading  import subprocess  import multiprocessing  src ="1.csv"  dst ="dst_thread.csv" thread = threading.Thread(target=shutil.copy,args=[src, dst])  thread.start()  thread.join() dst ="dst_multiprocessing.csv" process = multiprocessing.Process(target=shutil.copy,args=[src, dst])  process.start()  process.join()  cmd ="cp 1.csv dst_subprocess.csv"  status = subprocess.call(cmd, shell=True)

異步執行文件操作

搜索文件

復制和移動文件后,你可能需要搜索與特定模式匹配的文件名,Python提供了許多內置函數可以選擇。

Glob

glob模塊根據Unix shell使用的規則查找與指定模式匹配的所有路徑名,它支持使用通配符。

glob.glob(“ *。csv”)搜索當前目錄中所有具有csv擴展名的文件。使用glob模塊,還可以在子目錄中搜索文件。

>>>import glob  >>> glob.glob("*.csv")  [ 1.csv ,  2.csv ]  >>> glob.glob("**/*.csv",recursive=True)  [ 1.csv ,  2.csv ,  source/3.csv ]

os

os模塊功能十分強大,它基本上可以執行所有文件操作。我們可以簡單地使用os.listdir()列出目錄中的所有文件,并使用file.endswith()和file.startswith()來檢測模式,還可使用os.walk()來遍歷目錄。

import os  for file in os.listdir("."):      if file.endswith(".csv"):          print(file)  for root, dirs, files in os.walk("."):     for file in files:        if file.endswith(".csv"):           print(file)

搜索文件名——os

pathlib

pathlib 的功能與glob模塊類似。它也可以遞歸搜索文件名。與上文基于os的解決方案相比,pathlib代碼更少,并且提供了更多面向對象的解決方案。

from pathlib importPath  p =Path(".")  for name in p.glob("**/*.csv"): # recursive      print(name)

搜索文件名——pathlib

管理文件路徑

管理文件路徑是另一項常見的執行任務。它可以獲取文件的相對路徑和絕對路徑,也可以連接多個路徑并找到父目錄等。

相對路徑和絕對路徑

os和pathlib都能獲取文件或目錄的相對路徑和絕對路徑。

import os  import pathlib  print(os.path.abspath("1.txt"))  # absolute  print(os.path.relpath("1.txt"))  # relative  print(pathlib.Path("1.txt").absolute())  # absolute  print(pathlib.Path("1.txt"))  # relative

文件的相對和絕對路徑

聯接路徑

這是我們可以獨立于環境連接os和pathlib中的路徑的方式。pathlib使用斜杠創建子路徑。

import os  import pathlib  print(os.path.join("/home", "file.txt"))  print(pathlib.Path("/home") /"file.txt")

鏈接文件路徑

獲取父目錄

dirname()是在os中獲取父目錄的函數,而在pathlib中,只需使用Path().parent函數,就能獲取父文件夾。

import os  import pathlib  # relative path  print(os.path.dirname("source/2.csv"))  # source print(pathlib.Path("source/2.csv").parent)  # source  # absolute path  print(pathlib.Path("source/2.csv").resolve().parent)  # /Users/<...>/project/source  print(os.path.dirname(os.path.abspath("source/2.csv")))  # /Users/<...>/project/source

獲取父文件夾

“Python中最常見的文件操作技巧有哪些”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女