In this tutorial you will learn about Python I/O, how to open a file and how to read, write a file in Python.
File types supported by Python
Python has support for following types of files-
- Text files– Files where data is stored in the form of characters.
- Binary files– Files where data is stored in the form of bytes. Useful for storing images,
Opening a file
File in python is opened using built-in function open() which returns a file object. If the file cannot be opened, an OSError is raised. Syntax of open is as follows.
Description of arguments-
- filename is the path (absolute or relative to the current working directory) of the file to be opened.
- open_mode specifies the mode in which the file is opened. It is an optional argument and defaults to ‘r’ which means open for reading in text mode.
- buffering specifies the buffering policy.
- 0 means buffering is off (only allowed in binary mode)
- 1 means line buffering (only usable in text mode)
- integer > 1 indicates buffer size in bytes.
It is also an optional argument and default buffer size is 4096 or 8192 bytes.
- encoding specifies the name of the encoding used to decode or encode the file. This should only be used in text mode.
Modes for opening a file in Python
|‘r’||Open file for reading, starts from the beginning of the file. It is the default mode.|
|‘w’||Open file for writing. Any existing data in the file is deleted|
|‘x’||Opens for exclusive creation, failing if the file already exists|
|‘a’||Open for appending content to an already existing file. If file doesn’t exist a new file is created.|
|‘b’||Opens in binary mode|
|‘t’||Opens in text mode, it is the default mode.|
|‘+’||open for updating (reading and writing)|
Some examples of using open() function in Python.
# opens file using default mode which is ‘rt’ meaning reading a text file f = open(“abc.txt”) # opens file for writing in binary mode f = open(“abc.txt”, 'wb') # opens file for writing and reading in binary mode f = open(“abc.txt”, 'w+b') # opens file for reading and writing f = open(“abc.txt”, 'r+') # opens file for writing, existing content is deleted f = open(“abc.txt”, 'w')
Closing a file
Once you are done with file I/O operations you should close the file using the close() method. Closing a file immediately frees up any system resources used by it.
After a file object is closed, file object is not accessible any more. If you want to work with the file again, you need to open the file again using the open() function.
Python example to append to a file
Here is an example that opens a file in append mode and append content to the end of the file. Later same file is opened in read mode to read the file.
def write_file(fname): try: f = open(fname, 'a') f.write("This is a test file.\n") finally: f.close() def read_file(fname): try: f = open(fname, 'r') str = f.read() print('Content- ', str) finally: f.close() write_file('F:\\knpcode\\abc.txt') read_file('F:\\knpcode\\abc.txt')
In the above example you can see there is a lot of code just to ensure that the file is closed properly. But that try-finally block is required too to ensure that the file is always closed and the resources freed even if an exception is raised.
Another way and the recommended one is to use with keyword in Python when using file objects. By opening a file using with statement file is closed automatically after its suite finishes, even if an exception is raised at some point.
Syntax of using with is as follows-
using with open Python example
def read_file(fname): with open(fname, 'r') as f: s = f.read() print('Content- ', s) print('File closed- ', f.closed) read_file('F:\\knpcode\\abc.txt')
Using f.closed() you can check that the file has been automatically closed.
Python File methods
Here is a complete list of methods in class io.TextIOBase which is the base class for text streams. These are the methods you will use when you get a file object by opening a file in text mode.
|close()||Flush and close this stream.|
|closed()||True if the stream is closed.|
|fileno()||Return a file descriptor (an integer) of the stream|
|flush()||Flush the write buffers of the stream if applicable.|
|isatty()||Return True if the stream is interactive|
|read(n=-1)||Read and return at most n characters from the stream as a single str. If n is negative or None, reads until EOF.|
|readline(n=-1)||Read until newline or EOF and return a single str. If n is specified, at most n characters will be read.|
|readlines()||Read and return a list of lines from the stream.|
|readable()||Return True if the stream can be read from.|
|seek(offset, fromwhere)||Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by fromwhere.|
|seekable()||Return True if the stream supports random access.|
|tell()||Return the current stream position.|
|truncate(size=None)||Resize the stream to the given size in bytes.Resizes to current location if size is not specified.|
|writable()||Return True if the stream supports writing.|
|write(s)||Write the string s to the stream and return the number of characters written.|
|writelines(lines)||Write a list of lines to the stream.|
- Python Program to Read a File
- Python Program to Write a File
- Python Program to Append to a File
- Python Program to Check File or Directory Exists
- How to Delete File and Directory in Python
- How to Copy File in Python
- super() in Python With Examples
- Method Overloading in Python With Examples
That’s all for the topic Python I/O – Open, Read, Write Files. If something is missing or you have something to share about the topic please write a comment.
You may also like