2016-02-19 34 views
-1

現在我知道這裏有很多問題,並且我仔細研究了所有這些問題並嘗試瞭解它們,但是我無法適用於我的情況。根據以前對別人問題的回答,我想出了一些改進的代碼。然而,它有一個問題:如何將數據輸入到.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組數據。所以這是另一個問題。

任何幫助,將不勝感激;謝謝。

回答

2

每當您呼叫您的功能Main()您正在重設值y

所以流程是這樣的:

  1. 計劃開始,Main()運行。
  2. 用戶給出號碼2y等於0 -
  3. 現在函數Writefile被調用。完成後,它再次調用Main()
  4. 現在另一個y,不是你原來的y設置爲0
  5. 根據什麼回答你的用戶所賜,新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

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

相關問題