【问题标题】:Python : Using while loop with CSV headings 3.2 in appendPython:使用带有 CSV 标题 3.2 的 while 循环追加
【发布时间】:2015-07-02 02:12:41
【问题描述】:

我正在尝试通过在循环中附加到现有文件来一次构建一个 csv 文件。我还希望在文件顶部有列标题。有没有办法在构建文件时通过附加来获得标题。

这是我的代码:

while True:
  try:
    print("What class are you from? Between 1 to 3. ") # this is deciding which class the user is from
    Class = int(input()) #depending on the input, it goes to the correct class files to be stored as a CSV file
    if Class == 1:
        with open('Class 1.csv', 'a') as csvfile:
            fieldnames = ['Name', 'Score']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames) #this is for writing the headers
            writer.writeheader()
            writer.writerow({'Name': name, 'Score': score})
        break #this is to get out of the loop
    elif Class == 2:
        with open('Class 2.csv', 'a') as csvfile:
            fieldnames = ['Name', 'Score']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({'Name': name, 'Score': score})
        break
    elif Class == 3:
        with open('Class 3.csv', 'a') as csvfile:
            fieldnames = ['Name', 'Score']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({'Name': name, 'Score': score})
        break
    else:
        print("Please enter a number between 1 to 3.") #this loops if the user inputs a number too high
  except ValueError:
    print("Please enter a number between 1 to 3.")

【问题讨论】:

  • 每个文件应该有多少行?你似乎只写了一行。如果你定义一个像def writeForClass(class_number) 这样的函数而不是复制粘贴你的代码,你可能会更轻松。
  • 您能澄清一下您的代码实际执行的操作与您希望它执行的操作相比吗?目前还不清楚。另外,我在您的代码中看不到“追加”-追加是如何参与其中的?
  • 我想要它做的是继续依赖用户输入,以便随着程序一次又一次地重复使用而超时构建数据。
  • @DavidW "append" 在 ` with open('Class 1.csv', 'a') as csvfile:` 或者 append 的正确使用,如果在全部“追加”
  • 好的,我明白了。正如您所说,open 的“a”标志确实以附加模式打开文件。

标签: python csv append


【解决方案1】:

我相信您正在尝试确保标题只被写入一次(在文件顶部),并且每次循环迭代都会添加一行。我会做这样的事情:

while True:
  # "try" removed to keep this short - you can re-add it as you like
  print("What class are you from? Between 1 to 3. ") # this is deciding which class the user is from
  Class = int(input()) #depending on the input, it goes to the correct class files to be stored as a CSV file
  if Class == 1:
    filename = 'Class 1.csv'
  elif Class == 2:
    filename = # ... implement this, and class 3 etc

  file_exists = os.path.exists(filename) # check to see if the file has already been started (you'll need to import os.path too)

  with open(filename, 'a') as csvfile:
    fieldnames = ['Name', 'Score']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    if not file_exists:
      # only write the header if we've just created the file
      writer.writeheader()
    # but write the row every time
    writer.writerow({'Name': name, 'Score': score})

基本思想是在打开文件之前检查文件是否已经存在。如果不是你写标题。如果确实存在,您只需编写该行。

但是 - 我个人会尝试寻求一种解决方案,您可以创建一个变量来跟踪程序运行时 csv 文件中的内容,但只有在一切完成后才真正将其写入文件。它可能最终会比随手附加到文件更简单。

【讨论】:

  • 感谢您的帮助,我真的需要这个。
【解决方案2】:

基本上你可以在开始调用writeheader()/writerow()之前在CSV文件中写一些东西。

fieldnames = ['Name', 'Score']
with open('Class %d.csv' % class_number, 'a') as csvfile:
   csvfile.write('; This is a comment in the first line\n')
   writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
   writer.writeheader()
   ...

请注意,cmets 在 CSV 中是 not well-standardized。分号作为第一个字符通常被理解。

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2023-03-10
    • 2021-07-31
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2016-02-16
    • 2017-02-25
    相关资源
    最近更新 更多