[英]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.