如何将数据输入到.csv文件中的标签栏中
问题描述:
现在我知道这里有很多问题,并且我仔细研究了所有这些问题并尝试了解它们,但是我无法适用于我的情况。根据以前对别人问题的回答,我想出了一些改进的代码。然而,它有一个问题:如何将数据输入到.csv文件中的标签栏中
import sys
import os
import csv
def writefile():
print('Please enter the following: ')
a = input('Date Of The Fixture: ')
b = input('Stadium: ')
c = input('Opposition: ')
d = input('Goals For Leicester: ')
e = input('Goals Against Leicester: ')
f = input('Attendance: ')
with open("LCFC_League_Results.csv","w") as outfile:
outfile.write('Date of the Fixture, Stadium, Opposition, Goals for Leicester, Goals Against Leicester, Attendance\n')
for row in zip('Date of the Fixture', 'Stadium', 'Opposition', 'Goals for Leicester', 'Goals Against Leicester', 'Attendance'):
outfile.write('{}, {}, {}, {}, {}, {}\n'.format(a,b,c,d,e,f))
Main()
def readfile():
myFile = open("LCFC_League_Results.csv","r")
print("Reading File ...")
print(myFile.read())
myFile.close()
Main()
def Main():
print("Write To File - A")
print("Read The File - B")
print("Clear File - C")
print("Exit The Program - X")
Choice = input("What would you like to do with the file: ")
if Choice == "a" or Choice == "A":
x = int(input("How many matches do you want to input? "))
y = 0
while y<x:
writefile()
y = y+1
elif Choice == "B" or Choice == "b":
readfile()
elif Choice == "C" or Choice == "c":
os.remove("LCFC_League_Results.csv")
Main()
elif Choice == "X" or Choice == "x":
sys.exit()
Main()
有问题的部分是什么在子程序'writefile'下。如果我输入数据A,B,C,d,E,F的输出出来为:
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
a, b, c, d, e, f
为什么输出7项的行;我输入了一次信息,想要排成一行。加上,至少列被标记。作为一个方面,当它询问'你想输入多少匹配'时,无论输入什么数字,它总是只允许你输入1组数据。所以这是另一个问题。
任何帮助,将不胜感激;谢谢。
答
每当您呼叫您的功能Main()
您正在重设值y
。
所以流程是这样的:
- 计划开始,
Main()
运行。 - 用户给出号码
2
。y
等于0
- - 现在函数
Writefile
被调用。完成后,它再次调用Main()
。 - 现在另一个
y
,不是你原来的y
设置为0 - 根据什么回答你的用户所赐,新
y
被设置为0
只要一个Main()
被调用。
此外,你应该改变:
outfile.write('Date of the Fixture, Stadium, Opposition, Goals for Leicester, Goals Against Leicester, Attendance\n')
for row in zip('Date of the Fixture', 'Stadium', 'Opposition', 'Goals for Leicester', 'Goals Against Leicester', 'Attendance'):
outfile.write('{}, {}, {}, {}, {}, {}\n'.format(a,b,c,d,e,f))
要简单地说:
outfile.write('Date of the Fixture, Stadium, Opposition, Goals for Leicester, Goals Against Leicester, Attendance\n')
outfile.write('{}, {}, {}, {}, {}, {}\n'.format(a,b,c,d,e,f))
这仍然有标题总是被写的问题...
还有一点,您正在导入模块csv
,为什么不使用它? 最后,如果你继续使用python,请阅读pep-8
。
答
您的代码写在这里的七行:
for row in zip('Date of the Fixture', 'Stadium', 'Opposition', 'Goals for Leicester', 'Goals Against Leicester', 'Attendance'):
outfile.write('{}, {}, {}, {}, {}, {}\n'.format(a,b,c,d,e,f))
如果你只想要一排,除去for
循环。