簡體   English   中英

如何讓python打印整個文件而不是單行

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

我有一個只有一列數字的 .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_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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM