Python 如何将两个列表写入一个文件
我的代码在创建一个文件并将单词列表和数字列表写入文件时遇到问题。代码根本不创建文件。这是:Python 如何将两个列表写入一个文件,python,Python,我的代码在创建一个文件并将单词列表和数字列表写入文件时遇到问题。代码根本不创建文件。这是: sentence=input('please enter a sentence: ') list_of_words=sentence.split() words_with_numbers=enumerate(list_of_words, start=1) filename = 'fileoflists.txt' with open('fileoflists', 'w+') as file: fil
sentence=input('please enter a sentence: ')
list_of_words=sentence.split()
words_with_numbers=enumerate(list_of_words, start=1)
filename = 'fileoflists.txt'
with open('fileoflists', 'w+') as file:
file.write(str(list_of_words) + '/n' + str(words_with_numbers) + '/n')
谢谢参考。试试这个:
sentence=input('please enter a sentence: ')
list_of_words=sentence.split()
words_with_numbers=enumerate(list_of_words, start=1)
filename = 'fileoflists.txt'
with open('fileoflists', 'w+') as file:
file.write('\n'.join(['%s \n %s'%(x[0],x[1])
for x in zip(list_of_words, words_with_numbers)])+'\n')
参考资料。试试这个:
sentence=input('please enter a sentence: ')
list_of_words=sentence.split()
words_with_numbers=enumerate(list_of_words, start=1)
filename = 'fileoflists.txt'
with open('fileoflists', 'w+') as file:
file.write('\n'.join(['%s \n %s'%(x[0],x[1])
for x in zip(list_of_words, words_with_numbers)])+'\n')
运行代码时,它确实会创建文件,但是可以看到您正在使用
“fileoflists.txt”
的值在文件名中定义文件名,但是您不使用该参数,只创建一个文件(不是文本文件)
此外,它不会打印您期望的内容。对于列表,它打印列表的字符串表示形式,但是对于带有数字的单词,它打印由枚举
返回的迭代器的\uuuu str\uuu
请参阅下面代码中的更改:
sentence = input('please enter a sentence: ')
list_of_words = sentence.split()
# Use list comprehension to format the output the way you want it
words_with_numbers = ["{0} {1}".format(i,v)for i, v in enumerate(list_of_words, start=1)]
filename = 'fileoflists.txt'
with open(filename, 'w+') as file: # See that now it is using the paramater you created
file.write('\n'.join(list_of_words)) # Notice \n and not /n
file.write('\n')
file.write('\n'.join(words_with_numbers))
运行代码时,它确实会创建文件,但是可以看到您正在使用“fileoflists.txt”
的值在文件名中定义文件名,但是您不使用该参数,只创建一个文件(不是文本文件)
此外,它不会打印您期望的内容。对于列表,它打印列表的字符串表示形式,但是对于带有数字的单词,它打印由枚举
返回的迭代器的\uuuu str\uuu
请参阅下面代码中的更改:
sentence = input('please enter a sentence: ')
list_of_words = sentence.split()
# Use list comprehension to format the output the way you want it
words_with_numbers = ["{0} {1}".format(i,v)for i, v in enumerate(list_of_words, start=1)]
filename = 'fileoflists.txt'
with open(filename, 'w+') as file: # See that now it is using the paramater you created
file.write('\n'.join(list_of_words)) # Notice \n and not /n
file.write('\n')
file.write('\n'.join(words_with_numbers))
如果似乎没有创建任何文件,它可能位于其他位置?您是如何运行脚本的?无法复制-我运行了您的代码,它创建了fileoflists
文件。顺便说一句,您想要“\n”
换行吗?如果没有创建任何文件,它可能位于其他位置?您是如何运行脚本的?无法复制-我运行了您的代码,它创建了fileoflists
文件。顺便说一句,您想要“\n”
换行吗?OP使用str()
将列表转换为字符串,这就是他在问题中所要求的。您的解决方案似乎是编写列表内容的合理方式。。。但是我们可能需要澄清原始问题。OP使用str()
将列表转换为字符串,这就是他在问题中所要求的。您的解决方案似乎是编写列表内容的合理方式。。。但我们可能需要澄清原来的问题。