Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create and open files through Python?

I have a very elementary question, but I've tried searching past posts and can't seem to find anything that can help. I'm learning about file i/o in Python. All the tutorials I've seen thus far seem to skip a step and just assume that a file has already been created, and just being by saying something like handleName = open('text.txt', 'r'), but this leaves 2 questions unanswered for me:

  1. Do I have to create the file manually and name it? I'm using a Mac, so would I have to go to Applications, open up TextEdit, create and save the file or would I be able to do that through some command in IDLE?
  2. I tried manually creating a file (as described above), but then when I tried entering openfile = open('test_readline', 'r'), I got the error: IOError: [Errno 2] No such file or directory: 'abc'

Regarding the error, I'm assuming I have to declare the path, but how do I do so in Python?

like image 919
TheRealFakeNews Avatar asked Aug 17 '15 20:08

TheRealFakeNews


People also ask

Can you create files with Python?

How to Create Files in Python. In Python, you use the open() function with one of the following options – "x" or "w" – to create a new file: "x" – Create: this command will create a new file if and only if there is no file already in existence with that name or else it will return an error.

How do I open a Python file in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!


1 Answers

openfile = open('test_readline', 'w')

                                  ^^

Opening in write mode will create the file if it doesn't already exist. Now you can write into it and close the file pointer and it will be saved.

like image 200
vks Avatar answered Oct 03 '22 16:10

vks