简体   繁体   English

如何让python打印整个文件而不是单行

[英]how to make python print the whole file instead of just the single line

I have a .csv file that has just one column of numbers and I want to read each number in the column and print it in the console like this:我有一个只有一列数字的 .csv 文件,我想读取该列中的每个数字并将其打印在控制台中,如下所示:

1
2
3
4

here is the code that I have used:这是我使用的代码:

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

file_reference1.close()

what I expect is:我期望的是:

1
2
3

in the console.在控制台中。

But what I get is:但我得到的是:

1 

And the program stops.然后程序停止。 How do I make it print the whole file?如何让它打印整个文件?

You create a variable file_reference2 , but later call file_reference1.readlines() (notice the difference in variable names).您创建了一个变量file_reference2 ,但稍后调用file_reference1.readlines() (注意变量名称的差异)。 You are probably reading lines from a wrong file as this code works well for me if I change that line to file_reference2.readlines() like this:您可能正在从错误的文件中读取行,因为如果我将该行更改为file_reference2.readlines() ,则此代码对我来说效果很好:

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

file_reference2.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM