【问题标题】:Using Python, how can I loop through a csv file and print each cell?使用 Python,我如何遍历 csv 文件并打印每个单元格?
【发布时间】:2016-02-11 11:43:55
【问题描述】:

我正在上传一个 csv 文件,并希望遍历数据并将每个单元格插入数据库。这是python代码:

import csv
@app.route("/uploadcsv", methods=['POST'])
def uploadcsv():
    myfile = request.files['file']
    r = csv.reader(myfile)
    headers = r.next()
    for row in r:
        print str(row[0])
        print row[1]
        print row[2]
        print row[3]
        print row[4]
        print row[5]
        print row[6]
        print row[7]
        print row[8]
        # put into database
        return "OK"

csv 文件中当前有 3 行(稍后会更多),并且只打印第一行,如何打印所有行?

csv 文件是:

first_name,last_name,email,phone,designation,company,industry,tag,created_at
john,smith,john@example.com,1234567,some company,some industry,some tag, now()

【问题讨论】:

  • 是因为退货。将其从 for 循环中取出
  • 在移动到下一行之前返回“OK”
  • 只有两行,因为r.next() 调用,你的 for 循环从第二行开始,所以它应该只打印一行。回报仍然是您的主要问题

标签: python csv


【解决方案1】:

return "OK" 语句的缩进减少一级 - 就目前而言,它会在第一行打印后立即从uploadcsv() 返回,而不是像您预期的那样在 for 循环之后返回。

【讨论】:

  • 谢谢大家!很简单。现在工作正常。我是 Python 的新手,我不太了解缩进,非常感谢。
  • 很高兴为您提供帮助。在stackoverflow上,请按左侧的复选标记接受正确答案。
猜你喜欢
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 2019-02-26
  • 2021-09-12
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多