搜尋
首頁後端開發Python教學詳解關於Python中檔案的讀取與寫入


這篇文章主要介紹了詳解關於Python中文件的讀取和寫入,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧

從檔案讀取資料

讀取整個文件

這裡假設在當前目錄下有一個文件名為'pi_digits.txt'的文字文件,裡面的資料如下:

3.1415926535
8979323846
2643383279
with open('pi_digits.txt') as f: # 默认模式为‘r’,只读模式
    contents = f.read() # 读取文件全部内容
    print contents # 输出时在最后会多出一行(read()函数到达文件末会返回一个空字符,显示出空字符就是一个空行)
    print '------------'
    print  contents.rstrip() # rstrip()函数用于删除字符串末的空白
3.1415926535
8979323846
2643383279

------------
3.1415926535
8979323846
2643383279

逐行讀取

可以透過循環來實現逐行讀取資料:

with open('pi_digits.txt') as f:    
    for line1 in f:    
        print line1 # 每行末尾会有一个换行符
    print '------------'
    for line2 in f:    
        print line2.rstrip() # 此时文件已经读完,line2指向文本末尾,因此不会有输出
3.1415926535

8979323846

2643383279

------------

讀取檔案時相當於有一個指標在記錄讀取的位置,資料讀到哪,這個指標就指到哪邊,繼續讀取資料時會從該位置繼續讀取,因此上面程式碼中第二個循環中輸出為空。將上述程式碼稍加修改如下:

with open('pi_digits.txt') as f:  
  for line1 in f:    
      print line1    
  print '------------'
  
  with open('pi_digits.txt') as f: # 需要重新打开文本进行读取
    for line2 in f:     
       print line2.rstrip() # 删除字符串末尾的空白
3.1415926535

8979323846

2643383279

------------
3.1415926535
8979323846
2643383279

上述程式碼相當於第一次讀取完後關閉該檔案又重新開啟進行讀取。逐行讀取資料也可以用readline()函數,如下:

with open('pi_digits.txt') as f: 
    # readline()每一次读取一行数据,并指向该行末尾
    line1 = f.readline() # 读取第一行数据(此时已经指向第一行末尾)
    line2 = f.readline() # 从上一次读取末尾开始读取(第二行)

    print line1.rstrip()    print line2.rstrip()
3.1415926535
8979323846

有時候我們想要一次性讀取全部資料並且按分開儲存以便於後續的操作,當然用上面的循環可以實現,但python提供了更簡單的方法readlines():

with open('pi_digits.txt') as f: 
    lines = f.readlines() # 读取文本中所有内容,并保存在一个列表中,列表中每一个元素对应一行数据
print lines # 每一行数据都包含了换行符

print '------------'
for line in lines:  
  print line.rstrip()   
print '------------
'pi_str = '' # 初始化为空字符
for line in lines:
    pi_str += line.rstrip() #字符串连接
print pi_str
['3.1415926535\n', '8979323846\n', '2643383279\n']
------------
3.1415926535
8979323846
2643383279
------------
3.141592653589793238462643383279

寫資料到檔案

寫資料有幾種不同的模式,最常用的是w', 'a',分別表示擦除原有資料再寫入和將資料寫到原資料之後:

filename = 'write_data.txt'
with open(filename,'w') as f: # 如果filename不存在会自动创建, 'w'表示写数据,写之前会清空文件中的原有数据!
    f.write("I am Meringue.\n")
    f.write("I am now studying in NJTECH.\n")

此時會在目前路徑下建立一個'write_data.txt'的文字文件,並寫入文件中資料如下:

I am Meringue.
I am now studying in NJTECH.

下方繼續在該檔案中加入新資料:

with open(filename,'a') as f: # 'a'表示append,即在原来文件内容后继续写数据(不清楚原有数据)
    f.write("I major in Machine learning and Computer vision.\n")

#此時的檔案內容為:

I am Meringue.
I am now studying in NJTECH.
I major in Machine learning and Computer vision.

                

##################################################1都是

以上是詳解關於Python中檔案的讀取與寫入的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什麼是Numpy,為什麼對於Python中的數值計算很重要?什麼是Numpy,為什麼對於Python中的數值計算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

討論'連續內存分配”的概念及其對數組的重要性。討論'連續內存分配”的概念及其對數組的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具