1

I am trying to create a file that just writes the user's name to a file. I have written:

def main():
    f=open("name.txt","a")
    name=input("name:")
    f.writelines(name)
    f.close()
main()

I am wondering what I am missing in order for this to work because it does not save into a text file. Additionally I am using append so I can run this program more than once and continuously add names to it.

BarbaraJ
  • 21
  • 4

2 Answers2

0

The code works fine, but I suspect why it doesn't for you.

In the console, using input function, you need to tell the program that you're sending him a string. When it asks for the name, you shouldn't input for instance Bernard, but "Bernard".

You should use raw_input instead if you want to get rid of the " character.

PS : Have you tried running your program in the console using python command ? You would have seen the error message pop.

IMCoins
  • 3,149
  • 1
  • 10
  • 25
  • Even when I input "Bernard" with the quotations it still doesn't save. I also have python 3 so raw_input is just input for me – BarbaraJ Nov 30 '17 at 11:52
  • I do not have python 3.x installed. Your script does work for me in Python 2.7 though. Try doing `f.write(name)` instead of `f.writelines(name)` ? – IMCoins Nov 30 '17 at 11:54
  • f.write(name) still does not save my file unfortunately – BarbaraJ Nov 30 '17 at 11:56
0

input is used to read integers.

Use raw_input instead. A lot of people don't recommend using input.

It is possible a duplicate: link

Caio Cesar
  • 301
  • 3
  • 11
  • I have python 3.x so raw_input is not a function for me – BarbaraJ Nov 30 '17 at 12:12
  • Ops, didn't see it.. Anyway, just installed python 3.6.3 to give it a go, and your code works fine. What is the exception ? Or it just don't create/save the file ? – Caio Cesar Nov 30 '17 at 12:24
  • It just does not create and save the file – BarbaraJ Nov 30 '17 at 12:25
  • Have you tried to set a path for the file to be saved ? (I'm assuming you are running windows) Something like: path = "C:/Users//Desktop/name.txt" and then f = open(path, "a") Otherwise it will created the file in the dir you are running the .py – Caio Cesar Nov 30 '17 at 12:31