[英]python, write the contents of a list to a text file
I created a program in python that is used to create/edit user generated lists. 我用python创建了一个程序,该程序用于创建/编辑用户生成的列表。 I tried to create a save function that will save a list to a text file, but I'm having a problem. 我试图创建一个将列表保存到文本文件的保存功能,但是我遇到了问题。 It will create the text file but not write the content of the list to the text file. 它将创建文本文件,但不会将列表的内容写入文本文件。
#!/usr/bin/python
user_list = []
def banner():
logo = open('chlogo2', 'r')
for line in logo:
print line.strip('\n')
logo.close
main(user_list)
def save(user_list):
print "\nENTER A SAVE NAME.\nTHIS WILL BE SAVED AS A .TXT FILE.\n"
w = ("saves/" + raw_input("CNG>SAVE NAME> ") +".txt")
wr = open(w, 'w')
for i in user_list:
i.write(user_list, '\n')
main(user_list)
def prt(user_list):
print '\nCURRENT LIST -\n'
r = user_list
for line in r:
print line.strip('\n')
main(user_list)
def add(user_list):
print "\nTYPE AN ENTRY IN A 'POSITION' then 'ENTRY' FORMAT\nPRESS 'ENTER' WITHOUT AN INPUT TO RETURN TO THE MAIN FUNTION\n"
try:
x = int(raw_input("CNG>ADD>P> "))
y = raw_input("CNG>ADD>E> ")
x -= 1
user_list.insert(x, y)
add(user_list)
except:
main(user_list)
def main(user_list):
option = open('options')
for line in option:
print line.strip('\n')
option.close
opt = raw_input("CHG> ")
if opt == "list":
prt(user_list)
elif opt == 'banner':
banner()
elif opt == 'exit':
print ' '
elif opt == 'empty':
user_list = []
elif opt == 'add':
add(user_list)
elif opt == 'save':
save(user_list)
if __name__ == "__main__":
banner()
Your problem is in this line: 您的问题在这一行:
for i in user_list: i.write(user_list, '\\n')
Change it to this: 更改为此:
for i in user_list:
wr.write(i, '\n')
EDIT: And remove user_list
parameter from all of your functions because it is a global variable and you can access it from within your any function. 编辑:并从所有函数中删除user_list
参数,因为它是一个全局变量,您可以从任何函数中访问它。 This may also be a reason why your list not getting saved. 这也可能是您的列表未保存的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.