【发布时间】: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”标志确实以附加模式打开文件。