簡體   English   中英

使用 readlines() 打印 CSV 文件的每一行

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

否則你也可以使用其他方法作為枚舉

Python 為您的用例提供有用的內置函數。 例如enumerate ,它為可迭代對象中的每個項目產生一個連續的計數。

with open('Polly re-records.csv', 'r', encoding='ISO-8859-1') as file:
    for line_number, line in enumerate(file):
        print(line, line_number)

正如 drdalle 指出的那樣,使用內置的csv 模塊可能也是一個更好的主意,因為它還將處理 csv 編碼(例如,如果您有包含\n換行或其他轉義值的多行單元格。

暫無
暫無

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

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