TheRealFakeNews
TheRealFakeNews

Reputation: 8173

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?

Upvotes: 5

Views: 643

Answers (4)

bud
bud

Reputation: 485

Python will automatically use the default path.

import os
default_path = os.getcwd()          ## Returns the default path
new_path = "C:\\project\\"          ## Path directory
os.chdir(path)                      ## Changes the current directory

Once you change the path, the files you write and read will be in C:\project. If you try and read a project else where, the program will fail.

os.chdir is how you declare or set a path in python.

Upvotes: 1

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18467

  1. Do I have to create the file manually and name it?

Do you mean as a user, must you use existing tools to create a file, then return to Python to work on it? No. Python has all the tools necessary to create a file. As already explained by vks in their answer, you must open the file using a mode that will create the file if it doesn't exist. You've chosen read ('r') mode, which will (correctly) throw an error if there is no file to read at the location you've specified, which brings us to...

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

If you do not (if you say, e.g., "filename.txt"), Python will look in its current working directory. By default, this is the current working directory of the shell when you invoke the Python interpreter. This is almost always true unless some program has changed it, which is unusual. To specify the path, you can either hardcode it like you're doing to the filename:

open('/full/path/to/filename.txt')

or you can build it using the os.path module.


Example:

I created an empty directory and opened the Python interpreter in it.

>>> with open('test.txt'): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'test.txt'
>>> with open('test.txt', 'w'): pass
... 
>>> 

As noted, read mode (the default) gives an error because there is no file. Write mode creates a file for us with nothing in it. Now we can see the file in the directory, and opening with read mode works:

>>> os.listdir(os.getcwd())
['test.txt']
>>> with open('test.txt'): pass
... 
>>> # ^ No IOError because it exists now

Now I create a subdirectory called 'subdir' and move the text file in there. I did this on the command line but could have just as easily done it in Python:

>>> with open('test.txt'): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'test.txt'
>>> with open('subdir/test.txt'): pass
... 

Now we have to specify the relative path (at least) to open the file, just like on the command line. Here I "hardcoded" it but it can just as easily be "built up" using the os module:

>>> with open(os.path.join(os.getcwd(), 'subdir', 'test.txt')): pass

(That is just one way it could be done, as an example.)

Upvotes: 0

Tushar Gautam
Tushar Gautam

Reputation: 459

To be able to read from any file, the file must exist.Right? Now look here, file I/O has the syntax as shown below:

fp = open('file_name', mode) # fp is a file object

The second argument, i.e mode describes the way in which file will be used. w mode will open any existing file(if it exists) with the name as given in first argument. Otherwise it creates a new file with the same name. Beside, if you are on Windows and want to open a file in binary mode then append b to the mode. Eg. to open file to write in binary mode, use wb. Make a note that if you try to open any existing file in w (writing) mode then the existing file with the same name will be erased. If you want to write to the existing file without getting the old data erased, then use the a mode.It adds the new data at the end of the previous one.

fw = open('file_name','w')
fa = open('file_name','a') # append mode 

To know in detail you can refer the doc at Python File I/O. I hope this helps!

Upvotes: 2

vks
vks

Reputation: 67988

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.

Upvotes: 4

Related Questions