Python讀寫文件時非常流行的操作。Python讀文件有3種方法:read()、readline()和readlines()。Python寫文件有2種方法:write()和writelines()。
可以先編輯一下文件并寫入一些信息。在文本文件“example.txt”中寫入如下內(nèi)容:
- "Whenever you feel like criticizing anyone,"
- he told me,
- “just remember that all the people in this world
- haven’t had the advantages that you’ve had.
1、讀取文件
文件對象的read()方法用于讀取文件,當不傳遞任何參數(shù)時,read()方法將讀取整個文件:
- >>> with open('example.txt', 'r') as f: # 使用r模式
- ... print(f.read()) # 將讀取內(nèi)容打印出來
- ...
- "Whenever you feel like criticizing anyone,"
- he told me,
- “just remember that all the people in this world
- haven’t had the advantages that you’ve had.
read()方法也可以通過傳遞參數(shù)來指定讀取的字節(jié)數(shù):
- >>> with open('example.txt', 'r') as f:
- ... print(f.read(8)) # 讀取8個字節(jié)的數(shù)據(jù)
- ...
- "Wheneve
readline()方法用于讀取整行文本:
- >>> with open('example.txt', 'r') as f:
- ... print(f.readline()) # 僅讀取第一行
- ...
- "Whenever you feel like criticizing anyone,"
- >>> with open('example.txt', 'r') as f:
- ... for _ in range(3): # 讀取前三行文本
- ... print(f.readline())
- ...
- "Whenever you feel like criticizing anyone,"
- he told me,
- “just remember that all the people in this world
readline()方法同樣可以通過傳遞參數(shù)來指定讀取的字節(jié)數(shù):
- >>> with open('example.txt', 'r') as f:
- ... for _ in range(3):
- ... print(f.readline(6))
- ...
- "Whene
- ver yo
- u feel
readlines()方法用于讀取文件對象剩余的全部行,以列表的形式返回:
- >>> with open('example.txt', 'r') as f:
- ... print(f.readlines())
- ...
- ['"Whenever you feel like criticizing anyone," \n', 'he told me, \n', '“just remember that all the people in this world \n', 'haven’t had the advantages that you’ve had.']
- >>> with open('example.txt', 'r') as f:
- ... print(f.readline()) # 先使用readline()讀取一行
- ... print(f.readlines()) # 再使用readlines()讀取剩余的全部行
- ...
- "Whenever you feel like criticizing anyone,"
- ['he told me, \n', '“just remember that all the people in this world \n', 'haven’t had the advantages that you’ve had.']
2、寫入文件
使用Python寫入文件時,需要以寫“w”或附加“a”模式打開文件。需要謹慎使用“w”模式,因為它會覆蓋文件(如果文件已存在),該文件之前的所有數(shù)據(jù)都將被刪除。寫入字符串或字節(jié)序列(對于二進制文件)是使用write()方法實現(xiàn)的,返回寫入文件的字符數(shù):
- >>> with open('example.txt', 'w') as f: # 使用'w'模式
- ... f.write('I love Python')
- ... f.write('Hello!')
- ...
- 13
- 6
打開文本文件“example.txt”,會發(fā)現(xiàn)文件中的內(nèi)容已被覆蓋了,原先的所有數(shù)據(jù)都被刪除了,此時文件中的內(nèi)容是剛剛使用write()方法寫入的。
writelines()方法用于一次性寫入多行文件:
- >>> with open('example.txt', 'a') as f: # 使用'a'追加模式
- ... f.writelines(['Over and Over', 'DealBreaker'])
- ...
再次打開文本文件“example.txt”,會發(fā)現(xiàn)文件中原先的數(shù)據(jù)沒有被刪除,使用write()方法寫入的數(shù)據(jù)被追加到了原數(shù)據(jù)的末尾。
>>本文地址:http://uj2y2uok.com/zhuanye/2020/51378.html
聲明:本站稿件版權(quán)均屬中公教育優(yōu)就業(yè)所有,未經(jīng)許可不得擅自轉(zhuǎn)載。
1 您的年齡
2 您的學歷
3 您更想做哪個方向的工作?