import os
#List for text
mainlist = []
#Definitions
def main():
print("Please Input Data(Type 'Done' When Complete):")
x = input()
if x.lower() == 'done':
sort(mainlist)
else:
mainlist.append(x)
main()
def sort(mainlist):
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?:")
filename = input()
with open(filename + ".txt", "w") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
创建文件,并存储数据......但是finalstring的内容不会写入其中。该文件仍为空白。
答案 0 :(得分:0)
您多次调用sort(mainlist)
并且每次都会覆盖该文件。将打开模式更改为a
,如:
with open(filename + ".txt", "a") as f:
f.write(str(finalstring))
请参阅http://docs.python.org/3.2/tutorial/inputoutput.html#reading-and-writing-files