1

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

  • 1
    If no file seems to be created, it may be in another place? How did you run your script? – Daniel Feb 08 '17 at 18:38
  • 1
    Cannot duplicate - I ran your code and it created the `fileoflists` file. BTW, did you want `"\n"` newlines? – tdelaney Feb 08 '17 at 18:44

2 Answers2

0

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')
Community
  • 1
  • 1
sudo_coffee
  • 888
  • 1
  • 12
  • 26
  • 1
    OP uses `str()` to convert the lists to strings and that is literally what he asks for in his question. Your solution seems like a reasonable way to write the contents of the lists... but we may need clarification of the original question. – tdelaney Feb 08 '17 at 18:47
0

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

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.

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))
Gilad Green
  • 36,708
  • 7
  • 61
  • 95