现在我知道有很多问题就像这个问题一样,我已经查看了所有这些问题并尝试了解它们,但我不能将它应用到我的情况中。基于之前对其他人的问题的回答,我提出了一些改进的代码。但它存在问题:
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()
有问题的部分是子程序&#39; writefile&#39;下的内容。如果输入数据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行;我输入了一次信息,想要一行。在加号上,至少列标记。作为一方而言,当它询问时,您要输入多少匹配?&#39;,无论您输入什么号码,它始终只允许您输入1组数据。这是另一个问题。
任何帮助将不胜感激;感谢。
答案 0 :(得分:2)
每次调用您的函数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
。
答案 1 :(得分:2)
您的代码在这里写了七行:
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
循环。