Python三種讀取txt文件方式


簡單介紹

1.按行讀取方式readline()

readline()每次讀取文件中的一行,需要使用永真表達式循環讀取文件。但當文件指針移動到文件的末尾時,依然使用readline()讀取文件將出現錯誤。因此程序中需要添加1個判斷語句,判斷文件指針是否移動到文件的尾部,並且通過該語句中斷循環。

2.多行讀取方式readlines()

使用readlines()讀取文件,需要通過循環訪問readlines()返回列表中的元素。函數readlines()可一次性讀取文件中多行數據。

3.一次性讀取方式read()讀取文件最簡單的方法是使用read(),read()將從文件中一次性讀出所有內容,並賦值給1個字符串變量。

代碼:

# -*- coding: utf-8 -*-

file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

context = file.read()

print('read格式:')

print(context)

file.close()

print()

file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

context = file.readlines()

contextLines =''

for i in context:

    contextLines = contextLines + i

print('readlines格式:')

print(contextLines)

file.close()

print()

file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

contextLines =''

while True:

    context = file.readline()

    contextLines = contextLines + context

    if len(context) ==0:

    break

print('readline格式:')

print(contextLines)

file.close()

結果:

read格式:

hello world

hello China

readlines格式:

hello world

hello China

readline格式:

hello world

hello China


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM