简体   繁体   English

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

[英]Printing every line of the CSV file using readlines()

I am trying to print each line of a csv file with a count of the line being printed.我正在尝试打印 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

for the above code i am getting the following output:对于上面的代码,我得到以下 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

so instead of the ct starting from 1,in my output the first value is directly 479 which cant be possible unless the if statement is executed 478 times所以不是从 1 开始的 ct,在我的 output 中,第一个值直接是 479,除非 if 语句被执行 478 次,否则这是不可能的

what changes should i do or what is the logical flaw preventing the print statement from executing我应该做什么更改或阻止打印语句执行的逻辑缺陷是什么

It would probably be easier to leverage some of baked in python methods like enumerate()利用 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"))

With respect to what you might change and keep your code, the issue you are running into is you are calling readline() too often and discarding half the results.关于您可能更改和保留代码的内容,您遇到的问题是您过于频繁地调用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)

Else you can also use other methods as enumerate否则你也可以使用其他方法作为枚举

Python offers useful built-in functions for your use-case. Python 为您的用例提供有用的内置函数。 For example enumerate , which yields a consecutive count for each item in an iterable.例如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)

As drdalle noted, it might also be a better idea to use the built-in csv module as it will also handle csv encodings (eg if you have multi-line cells containing \n wrapped or other escaped values.正如 drdalle 指出的那样,使用内置的csv 模块可能也是一个更好的主意,因为它还将处理 csv 编码(例如,如果您有包含\n换行或其他转义值的多行单元格。

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

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