2017-04-26 28 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()

相关问题