【问题标题】:How do I read a text file line-by-line the "Pythonic" way如何以“Pythonic”方式逐行读取文本文件
【发布时间】:2018-05-02 07:43:33
【问题描述】:

我意识到这是一个常见且简单的问题,以前曾有人问过。我能够使用 dawg 的以下帖子中的伪 C 方法完成我的项目。我使用了“while True”并测试了一个空行。
read a text file line by line

IDE 警告未使用局部变量 line。将变量 s 更改为 line 对输出没有影响。 但是 dawg 建议的 Pytonic 方式似乎跳过了行。我已经取出了我在方法中执行的所有处理(将文本转换为 int,将数据放入元组列表并对其进行排序),并为这篇文章重写了文本文件。类似的结果。

我也尝试过 sys.stdin 建议,但没有保存这些结果。

显然,我是 Python3.5 的初学者。

# iofile_test3.py

with open('test_read_file.txt', 'r') as f:
for line in f:
    # read a line from file
    s = f.readline()
    print(s)


#test_read_file,txt
First line
Second line
Third line
Fourth and last line

######output#####
.Python 3.5.2 (default, Sep 14 2017, 22:51:06) 

`>>>

Second line

Fourth and last line


>>> 

我使用的是 Pycharm 17.3 社区版,但也尝试了这段代码与 Idle 相同的输出。第 1 行和第 3 行似乎被跳过了。我的操作系统是 Linux Mint。

【问题讨论】:

    标签: python-3.x file-io


    【解决方案1】:

    这些行被跳过,因为您将它们扔掉而不打印它们。通常的方法是不要忽略它们:

    with open('test_read_file.txt', 'r') as f:
        for line in f:
            print(line)
    

    【讨论】:

    • 好的。所以 for 行读取一次,readline 再次读取。
    猜你喜欢
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多