【问题标题】:Printing every line of the CSV file using readlines()使用 readlines() 打印 CSV 文件的每一行
【发布时间】:2023-01-26 23:38:26
【问题描述】:

我正在尝试打印 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

对于上面的代码,我得到以下输出:

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,在我的输出中第一个值直接是 479,除非 if 语句被执行 478 次,否则这是不可能的

我应该做什么更改或阻止打印语句执行的逻辑缺陷是什么

【问题讨论】:

    标签: python csv readline


    【解决方案1】:

    利用一些支持 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("
    "))
    

    【讨论】:

      【解决方案2】:
      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)
      

      否则你也可以使用其他方法作为枚举

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 2017-04-21
        • 2017-04-24
        • 1970-01-01
        • 2014-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多