如何将两个列表写入文件

时间:2017-02-08 18:34:45

标签: 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:
    file.write(str(list_of_words) + '/n' + str(words_with_numbers) + '/n')

感谢

2 个答案:

答案 0 :(得分:0)

参考this question for info。试试这个:

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')

答案 1 :(得分:0)

运行你的代码确实创建了文件,但是看到你在filename中定义了文件名,其值为"fileoflists.txt"但是你不使用那个参数而只是创建一个文件(不是文本文件)。

此外,它不会打印您所期望的内容。对于列表,它打印列表的字符串表示,但对于words_with_numbers,它打印__str__返回的迭代器的enumerate

请参阅以下代码中的更改:

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))