我的代码出现了问题,它的目的是创建一个文件,并将单词列表和数字列表写入文件中。代码根本不会创建文件。这就是它:
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')谢谢
发布于 2017-02-09 02:44:16
参考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')发布于 2017-02-09 02:44:26
运行您的代码时,它确实创建了文件,但是可以看到您在filename中使用"fileoflists.txt"的值定义了文件名,但是您没有使用该参数,而只是创建了一个文件(而不是文本文件)。
此外,它也不会打印您所期望的内容。对于列表,它打印列表的字符串表示,但是对于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))https://stackoverflow.com/questions/42121014
复制相似问题