简体   繁体   English

如何将两个列表写入文件

[英]how to write two lists into a file

I am having trouble with my code which is meant to create a file and write a list of words and a list of numbers into the file. 我的代码有问题,这意味着要创建一个文件,并在文件中写入单词列表和数字列表。 The code does not create a file at all. 代码根本不会创建文件。 Here it is: 这里是:

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

thanks 谢谢

Reference this question for info . 请参考此问题以获取信息 Try this: 尝试这个:

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

Running your code it does create the file but see that you are defining the file name in filename with the value of "fileoflists.txt" but then you do not use that parameter but just create a file (not a text file). 运行代码确实创建了文件,但是看到你在文件名中定义了文件filename ,其值为"fileoflists.txt"但是你不使用那个参数而只是创建一个文件(不是文本文件)。

Also it does not print what you are expecting. 它也不会打印出您期望的内容。 for the list it prints the string representation of the list but for the words_with_numbers it prints the __str__ of the iterator returned by the enumerate . 对于列表,它打印列表的字符串表示,但对于words_with_numbers它打印enumerate返回的迭代器的__str__

See changes in code bellow: 请参阅下面的代码更改:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM