日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python面試題之read、readline和readlines的區(qū)別詳解_python

作者:YZL40514131 ? 更新時間: 2022-09-17 編程語言

一、read

可以一次性讀取文件中所有內(nèi)容

1.txt文件內(nèi)容

??語法:

file.read([size])

例1:file.read():會將所有的內(nèi)容讀取出來

with open('1.txt','r') as file:
    content=file.read()
    print(content)

執(zhí)行結(jié)果:

file.read():是從文件的頭部開始讀取的。如果想要讀取部分內(nèi)容,可以先使用文件對象的seek()方法將文件的指針移動到新的位置,然后再應(yīng)用read(size)方法讀取。

seek()方法的基本語法格式:

file.seek(offset[,whence])
file:表鎖已經(jīng)打開的文件
offset:用于指定移動的字符個數(shù)
whence:用于指定從什么位置開始計算,值為0表示從文件頭開始計算,1表示從當(dāng)前位置開始計算,2表示從文件末尾開始計算,默認(rèn)為0

例2:讀取部分內(nèi)容

with open('1.txt','r') as file:
    file.seek(22)
    content=file.read()
    print(content)

執(zhí)行結(jié)果:

例3:file.read(size):表示讀取size個字符

with open('1.txt','r') as file:
    file.seek(22)
    content=file.read(10)
    print(content)

執(zhí)行結(jié)果:

二、readline

每次讀取一行數(shù)據(jù)

??格式:

file.readline()
file:打開的文件對象

例4:file.readline()讀取一條數(shù)據(jù)

with open('1.txt','r') as file:
    content=file.readline()
    print(content)

執(zhí)行結(jié)果:

例5:通過循環(huán)將文件中的數(shù)據(jù)全部讀取出來

with open('1.txt','r') as file:
    number=0
    while True:
        number+=1
        content=file.readline()
        if content=='':
            break
        print(number,content,end='\n')

執(zhí)行結(jié)果:

三、readlines

讀取全部行,返回的是一個字符串列表,每個元素為文件的一行內(nèi)容

??語法:

file.readlines()
file:打開的文件

例6:讀取全部行

with open('1.txt','r') as file:
    content=file.readlines()
    print(content)

執(zhí)行結(jié)果:

例7:將列表元素逐行輸出

with open('1.txt','r') as file:
    content=file.readlines()
    for index,item in enumerate(content):
        print(index,item)

執(zhí)行結(jié)果:

總結(jié)

  1. .read() 每次讀取整個文件,它通常將讀取到底文件內(nèi)容放到一個字符串變量中,也就是說 .read() 生成文件內(nèi)容是一個字符串類型。
  2. .readline()每只讀取文件的一行,通常也是讀取到的一行內(nèi)容放到一個字符串變量中,返回str類型。
  3. .readlines()每次按行讀取整個文件內(nèi)容,將讀取到的內(nèi)容放到一個列表中,返回list類型。

原文鏈接:https://blog.csdn.net/YZL40514131/article/details/125609673

欄目分類
最近更新