47 - read、readline 和 readlines 方法的區別

1. 如何打開和讀取文本文件內容

f = open('./files/readme.txt', 'r')
print(type(f))
# print(f.read())
# f.close()
<class '_io.TextIOWrapper'>

2. 使用 open函數打開文件,並返回一個 IO對象,該對象有3個用於讀取文件的方法: read、readline 和 readlines。請使用代碼描述這 3個方法的區別

# read: 讀取文件的全部內容
print(f.read())
f.close()
hello world
I love you
How are you?
f = open('./files/readme.txt', 'r')
f.read(3) # 如果指定參數n,會讀取前n個字符
f.close()
f = open('./files/readme.txt', 'r')
f.seek(6)
print(f.read(5))
f.close()
world
# readline
# 讀取一行
f = open('./files/readme.txt', 'r')
print(f.readline())
print(f.readline())
f.close()
hello world

I love you
f = open('./files/readme.txt', 'r')
print(f.readline(2)) # 如果指定n,當n 比當前行字符個數小
print(f.readline(20)) # 如果超過當前行字符個數,那麼最多讀取當前行的內容
f.close()
he
llo world
# readlines
# 返回列表
f = open('./files/readme.txt', 'r')
print(f.readlines())
f.close()
['hello world\n', 'I love you\n', 'How are you?']
f = open('./files/readme.txt', 'r')
print(f.readlines(3)) # 如果指定n,只會讀取行字符個數之和大於n 的行
f.close()
['hello world\n']
f = open('./files/readme.txt', 'r')
print(f.readlines(12)) # 如果指定n,只會讀取行字符個數之和大於n 的行
f.close()
['hello world\n', 'I love you\n']

48 - 在json 序列化時如何處理日期類型的值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章