题目:
将文件中数据按行读取出来,放进列表中。
视频教程:
Python入门题035:按行读取文件(3种方法)
代码:
from pathlib import Path
file_example = Path('./示例文件.txt')
with file_example.open() as fp:
lines = fp.readlines()
lines = [line.rstrip() for line in lines]
print('方法一:', lines)
# 适合读取大文件,比如 1G
with file_example.open() as fp:
lines = []
for line in fp:
lines.append(line.rstrip())
print('方法二:', lines)
with file_example.open() as fp:
lines = []
while line := fp.readline():
lines.append(line.rstrip())
print('方法三:', lines)
页面更新:2024-03-01
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号