首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将两个列表写入一个文件

如何将两个列表写入一个文件
EN

Stack Overflow用户
提问于 2017-02-09 02:34:45
回答 2查看 565关注 0票数 1

我的代码出现了问题,它的目的是创建一个文件,并将单词列表和数字列表写入文件中。代码根本不会创建文件。这就是它:

代码语言:javascript
运行
复制
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')

谢谢

EN

回答 2

Stack Overflow用户

发布于 2017-02-09 02:44:16

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

代码语言:javascript
运行
复制
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')
票数 0
EN

Stack Overflow用户

发布于 2017-02-09 02:44:26

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

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

请参见下面代码中的更改:

代码语言:javascript
运行
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42121014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档