Python中的read、readline和readlines都是用來讀取文件的方法,但是它們有一些不同的特點:
# 創(chuàng)建一個文件對象file = open('test.txt', 'r')# 使用read()方法讀取文件內(nèi)容content = file.read()print('使用read()方法讀取文件內(nèi)容:')print(content)print(type(content))# 關閉文件對象file.close()# 重新打開文件對象file = open('test.txt', 'r')# 使用readline()方法讀取文件第一行內(nèi)容line = file.readline()print('使用readline()方法讀取文件第一行內(nèi)容:')print(line)print(type(line))# 關閉文件對象file.close()# 重新打開文件對象file = open('test.txt', 'r')# 使用readlines()方法讀取文件所有行內(nèi)容lines = file.readlines()print('使用readlines()方法讀取文件所有行內(nèi)容:')print(lines)print(type(lines))# 關閉文件對象file.close()
輸出結(jié)果如下:
使用read()方法讀取文件內(nèi)容:Hello, this is a test file.It has three lines of text.The end.<class 'str'>使用readline()方法讀取文件第一行內(nèi)容:Hello, this is a test file.<class 'str'>使用readlines()方法讀取文件所有行內(nèi)容:['Hello, this is a test file.\n', 'It has three lines of text.\n', 'The end.']<class 'list'>