简体   繁体   中英

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.

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:

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

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()

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.

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. For example enumerate , which yields a consecutive count for each item in an iterable.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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