Python入门题035:按行读取文件(3种方法)

题目:

将文件中数据按行读取出来,放进列表中。

视频教程:

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

标签:入门   放进   文件   示例   视频教程   题目   适合   代码   方法   数据   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top