【发布时间】: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