2017-04-26 26 views
-2
file = open("My File.txt",'a+') 
for i in range(0,5): 
    cdtitle = input("Enter CD Title: ") 
    while cdtitle != "##": 
     cdartist = input("Enter CD artist: ") 
     cdlocation = input("Enter CD location: ") 
     file.append(cdtitle-----cdartist-----cdlocation) 

file.close()如何編寫特定程序的輸出並使用python將其保存在文件中?

> 據我

+0

其中*特別節目*? –

+0

你使用file.write(some_string),而不是追加... – Copperfield

+2

你也陷入了死循環,因爲你不會在'while'循環中改變'cdtitle' – MooingRawr

回答

1

使用write,而不是追加。

也連接字符串,不要使用減號-符號。

file.write("\n".join([cdtitle, cdartist, cdlocation)) 

上面還會將標題,藝術家和位置放在文件的新行中。

您還應該重置cdstatus的狀態,以便循環不是無限的。

file = open("My File.txt",'a+') 
for i in range(0,5): 
    cdtitle = input("Enter CD Title: ") 
    while cdtitle != "##": 
    cdartist = input("Enter CD artist: ") 
    cdlocation = input("Enter CD location: ") 
    file.write("\n".join([cdtitle, cdartist, cdlocation)) 
    cdtitle = "##" 
+1

你也可以''\ n'.join'而不是字符串連接。 :) – MSeifert

+0

不錯,我編輯它在:) – 2017-04-26 18:24:02

+0

做這樣的事情是更好地簡單地改變'while'爲'if' – Copperfield

0

你的腳本在while cdtitle != "##":上有一個無限循環。
您應該使用file.write()而不是file.append(),其中afaik不存在。

file = open("My File.txt",'a') 
for i in range(0,5): 
    cdtitle = input("(## to Exit) Enter CD Title: ") 
    if cdtitle == "##" : break 
    cdartist = input("Enter CD artist: ") 
    cdlocation = input("Enter CD location: ") 
    file.write("{}-----{}-----{}\n".format(cdtitle,cdartist,cdlocation)) 

file.close() 
-1

有一種直接寫入文件的簡單方法。

1)Save your python script as .py 
2)Open command prompt where your python file is present. 
3)Type -> scriptName.py > filename.txt 
4)Press enter 
0
## I managed this 
FileHandle = open("My File.txt",'w') 
cdtitle = input("Enter Cd title: ") 
while cdtitle != "##": 
    cdartist = input("Enter CD Artist: ") 
    cdlocation = input("Enter CD Loation: ") 
    FileHandle.write(cdtitle + ':' + cdartist + ':' + cdlocation) 
    cdtitle = input("Enter CD title: ") 

FileHandle.close()

相關問題