【问题标题】:how to make python print the whole file instead of just the single line如何让python打印整个文件而不是单行
【发布时间】:2019-04-02 18:03:10
【问题描述】:

我有一个只有一列数字的 .csv 文件,我想读取列中的每个数字并将其打印在控制台中,如下所示:

1
2
3
4

这是我使用的代码:

file_reference2 = open("file1.csv", "r")
read_lines1 = file_reference1.readlines()
for line1 in read_lines1:
    print(line1)

file_reference1.close()

我的期望是:

1
2
3

在控制台中。

但我得到的是:

1 

然后程序停止。如何让它打印整个文件?

【问题讨论】:

  • 您的file_reference1 定义在哪里?还是打错字了?
  • 为什么不希望它打印4
  • 无法复制。自从您将 open 分配给 file_reference2 后,这似乎是一个错字,但您使用的是 file_reference1
  • 我在发布有关解析文件时通常会做的事情是; 0) 将问题缩小到问题仍然可重现的最少量的代码和数据,1) Python 版本,python --version 2) 显示全部或部分文件,cat /path/to/file 3) 显示所有代码,@987654332 @, 4) 显示在 CLI 上运行代码的输出。这将更容易准确地理解正在发生的事情。

标签: python python-3.x missing-data readlines


【解决方案1】:

您创建了一个变量file_reference2,但后来调用了file_reference1.readlines()(注意变量名称的不同)。您可能正在从错误的文件中读取行,因为如果我像这样将该行更改为 file_reference2.readlines(),则此代码对我很有效:

file_reference2 = open("file1.csv", "r") 
read_lines1 = file_reference2.readlines() 
for line1 in read_lines1: 
    print(line1)

file_reference2.close()

【讨论】:

    猜你喜欢
    • 2018-11-21
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多