2014-10-10 77 views
0

我對Python相當陌生,而且對於使用文件I/O方面我還很陌生。我很難想出如何將數組寫入一個新的txt文件,其名稱由用戶輸入。下面是我寫的代碼:將數組寫入到包含請求名稱的txt文件

def main(): 
    # Opens file 
    fh = open("A5Nums.txt", "r") 
    array = [ ] 
    # Reads numbers into an array 
    for line in fh.readlines(): 
     for i in line.split(): 
      array.append(int(i)) 
    # Prints the array 
    print (array) 

    # Reverses the array 
    array.reverse() 

    # Prints the reversed array 
    print (array) 

    # Closes the input file 
    fh.close()  

main() 

扭轉數組後,我需要從用戶的輸出文件請求的名稱,然後根據他們輸入的內容保存文件。任何幫助,將不勝感激!謝謝!

回答

1

您可以從用戶那裏得到的文件名在Python 3.x的

outfile = input("Please name your output file") 

或Python 2.x的

outfile = raw_input("Please name your output file") 

然後寫這樣

with open(outfile, "w+") as fOut: 
    strArray = list(map(str, array)) 
    fOut.writelines(strArray) 
+0

我會需要把這個主要? – Ben 2014-10-10 17:09:49

+0

是的,在'fh.close()'之後,你可以放入這幾行。 – CoryKramer 2014-10-10 17:12:44

+0

它給我一個類型錯誤。必須是str,而不是int。 – Ben 2014-10-10 17:21:20