[英]Printing every line of the CSV file using readlines()
我正在尝试打印 csv 文件的每一行,其中包含正在打印的行数。
with open('Polly re-records.csv', 'r',encoding='ISO-8859-1') as file: #file1 path
ct=0
while True:
ct+=1
if file.readline():
print(file.readline(),ct)
else:
break #break when reaching empty line
对于上面的代码,我得到以下 output:
lg1_1,"Now lets play a game. In this game, you need to find the odd one out.",,,,,,,,,,,,,,,,,,,,,,,,
479
sc_2_1,Youve also learned the strong wordsigns and know how to use them as wordsigns. ,,,,,,,,,,,,,,,,,,,,,,,,
480
所以不是从 1 开始的 ct,在我的 output 中,第一个值直接是 479,除非 if 语句被执行 478 次,否则这是不可能的
我应该做什么更改或阻止打印语句执行的逻辑缺陷是什么
利用 python 中的一些方法可能会更容易,例如enumerate()
with open("Polly re-records.csv", "r") as file_in:
for row_number, row in enumerate(file_in, start=1):
print(row_number, row.strip("\n"))
关于您可能更改和保留代码的内容,您遇到的问题是您过于频繁地调用readline()
并丢弃了一半的结果。
with open('Polly re-records.csv', 'r',encoding='ISO-8859-1') as file: #file1 path
ct=0
while True:
ct+=1
row = file_in.readline().strip()
if row:
print(row, ct)
else:
break #break when reaching empty line
import csv
with open("data.csv", 'r') as file:
csvreader = csv.reader(file)
header = next(csvreader)
for x in range(len(csvreader)):
print(csvreader[x], x)
否则你也可以使用其他方法作为枚举
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.