如何将两个列表写入fi

2024-10-03 06:21:55 发布

您现在位置: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')

谢谢


Tags: 文件of代码列表inputwith数字单词
2条回答

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

运行代码时,它确实创建了文件,但是可以看到您在filename中用"fileoflists.txt"的值定义了文件名,但是您不使用该参数,只创建了一个文件(不是文本文件)。在

它也不会打印出你期望的结果。对于list,它打印列表的字符串表示,但是对于words_with_numbers,它打印由enumerate返回的迭代器的__str__。在

参见以下代码更改:

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

相关问题 更多 >