13. Python 檔案操作

來源:互聯網
上載者:User

標籤:python   檔案處理

1.      簡單的讀取檔案內容(codecs的使用)

目前的目錄下有個1.txt的文檔

開啟檔案的步驟:

    import codecs

(1)open檔案

    f = codecs.open(‘1.txt‘)

(2)檔案操作(讀或寫)

    print (f.read())

(3)關閉檔案

    f.close()

結果如下:

650) this.width=650;" src="https://s5.51cto.com/oss/201710/27/88ed8dd2b331713e6ead2994b8ab2674.png" title="1.png" alt="88ed8dd2b331713e6ead2994b8ab2674.png" />

這個方法等於把整個檔案拿出來,當成一個字串來使用,後期用正則匹配的時候,非常方便、適用。

【codecs 這個模組,是open開啟檔案的時候,引入這個模組,用途:解決檔案亂碼的。推薦以後在讀寫的時候使用這個模組】


如果設:

    text = f.read()

查看text的類型:

    print (type(text))

查看到類型是"str"(字串)


類型是字串,我們就可以使用字串的方法:

    result = text.replace(‘1‘, ‘A‘)

    print (result)



2.      寫入一個新的檔案

import codecs

f = codecs.open(‘2.txt‘, ‘w‘)

f.write(‘hello world!\n‘)

f.write(‘hello {0}!\n‘.format(‘LLN‘))

f.write(‘you cool!\n‘)

f.write(‘I like it!\n‘)

f.close()

注釋:

# open(filename, mode)

# mode有幾個參數:

    r讀取

    w寫入

    b二進位

    a追加


3.     檔案操作常用用法

readlins() 方法:

此方法,讀取檔案,把每一行都變成單獨的字串,並放入到一個列表中去,第一行為列表的第一個元素,以此類推。

舉例:

import codecs

f = codecs.open(‘1.txt‘, ‘rb‘)

t_list = f.readlines()

print (t_list[0]

print (f.readlines())

f.close()

返回結果:

1111111111第一行

[]

注釋:

為什麼 print (f.readlines()) 會返回空列表?

因為之前readlines()已經將檔案讀到末尾了,下次再用readlines()方法讀的時候,會從文章最末尾開始讀取,所以結果為[]。


readline() 方法:

此方法,讀取檔案,每一個readline()唯讀取一行,游標會停留在下一行的開頭;

在執行下一個readline()的時候,會從游標處讀取當前這一行。

import codecs

f = codecs.open(‘1.txt‘, ‘rb‘)

print (f.readline())

print (f.readline())

print (f.readline())

print (f.readline())

print (f.readline())

f.close()

返回結果:

1111111111

aaaaaaaaaa

2222222222

bbbbbbbbbb

3333333333


next()方法:

對比:

readline() 讀取檔案一行內容,返回一個字串

next() 讀取檔案下一行內容返回一個字串


write()方法和writelines()方法:

write() 必須傳入一個(整個)字串

writelines() 必須傳入一個序列


舉例1:

import codecs

f = codecs.open(‘2.txt‘, ‘wb‘)

f.write(‘hello lili\n cccccccc\n aaaaaaaaaa\n‘)  ## 一個整的字串

f.close()

可以看到多出來一個檔案:

650) this.width=650;" src="https://s1.51cto.com/oss/201710/27/6507bdf01a81599da6bbac9cec4fbd81.png" title="2.png" alt="6507bdf01a81599da6bbac9cec4fbd81.png" />

檔案內容:

650) this.width=650;" src="https://s1.51cto.com/oss/201710/27/b6cc42cf2ca0d2ab0e695229fab046d1.png" title="3.png" alt="b6cc42cf2ca0d2ab0e695229fab046d1.png" />


舉例2:

import codecs

f = codecs.open(‘2.txt‘, ‘wb‘)

f.writelines([‘aaaaa\n‘,‘bbbbbbbb\n‘,‘cccccccc‘]) ##傳入一個列表(序列)

f.close()

可以看到多出來一個檔案的內容:

650) this.width=650;" src="https://s4.51cto.com/oss/201710/27/5cfa3041723de9997e3016db1c9f5143.png" title="4.png" alt="5cfa3041723de9997e3016db1c9f5143.png" />


tell()方法:

提示當前游標落在哪個字元位置上

舉例:

import codecs

f = codecs.open(‘3.txt‘, ‘wb‘)

f.writelines([‘aaaaa\n‘,‘bbbbbbbb\n‘,‘cccccccc‘])

print f.tell()

f.close()

返回:

23


seek()方法:

指定游標的位置,seek(0)是移動到文章開頭

舉例:

import codecs

f = codecs.open(‘3.txt‘, ‘wb‘)

f.writelines([‘aaaaaaaaaaaaaaa\n‘,‘bbbbbbbbbbbbb\n‘,‘cccccccc\n‘])

print f.tell()

f.seek(0)

f.write(‘sssssssssssssssss‘)##重新寫入

f.close()

返回結果:

sssssssssssssssssbbbbbbbbbbbb

cccccccc

從結果看出,將游標移動到開頭後,並在開頭寫入字串,並替換掉原有字串對應的位置的字元,檔案總長度不變。


4.with的特殊用法

舉例:

import codecs

with codecs.open(‘1.txt‘, ‘rb‘) as f:

    print (f.read())

這種方法不需要寫close(),在執行完成後,會自動關閉檔案。


拓展:

列印檔案指定行的內容:

方法一:

import codecs

with codecs.open(‘1.txt‘, ‘rb‘) as f:

    for line, value in enumerate(f):

        if line == 4-1:#列印第四行的內容,下標為3

            print (value)


方法二:(python有個內建的方法)

import linecache

count = linecache.getline(filename,linenum)


舉例:

import linecache

count = linecache.getline(‘1.txt‘,4)   ##下標為3

print count

本文出自 “筆記空間” 部落格,請務必保留此出處http://286577399.blog.51cto.com/10467610/1976728

13. Python 檔案操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.