如何将数据输入.csv文件中的标记列

时间:2016-02-19 21:05:21

标签: python csv iteration

现在我知道有很多问题就像这个问题一样,我已经查看了所有这些问题并尝试了解它们,但我不能将它应用到我的情况中。基于之前对其他人的问题的回答,我提出了一些改进的代码。但它存在问题:

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组数据。这是另一个问题。

任何帮助将不胜感激;感谢。

2 个答案:

答案 0 :(得分:2)

每次调用您的函数Main()时,您正在重置y的值。

所以流程是这样的:

  1. 程序启动,Main()运行。
  2. 用户提供号码2y等于0 -
  3. 现在调用函数Writefile。完成后,它再次调用Main()
  4. 现在另一个y,而不是您原来的y设置为0.
  5. 根据用户的回答,只要y被调用,新的0就会设置为Main()
  6. 另外,你应该改变:

    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循环。