Python has several methods for creating, reading, updating, and deleting files. In this post, you will learn about file operations in Python. More specifically, opening a file, reading from that file, writing into that file, closing the file.
File Handling In Python
Python allows users to handle files, i.e., to read and write files, along with many other file handling options, to operate on files. Before you can read, append or write to a file, you will first have to it using Python’s built-in open() function.
Python File open() Function
The main function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file in Python.
‘r’ – Read – Default value. Opens a file for reading, error if a file does not exist.
‘a’ – Append – Opens a file for appending, creates the file if a file does not exist.
‘w’ – Write – Opens a file for writing, creates the file if a file does not exist.
‘x’ – Create – Creates the specified file, returns an error if a file exists.
Also, you can specify if the file should be handled as binary or text mode.
‘t’ – Text – Default value. Text mode.
‘b’ – Binary – Binary mode (e.g. images).
Let us see an example.
Create two files called add.txt and app.py file in the same folder and write the following code inside the add.txt file.
hello world this is python
Now, add the following code inside an app.py file.
# app.py mainFile = 'add.txt' file = open(mainFile, 'r') for text in file: print (text)
You need to make sure the file exists, or else you will get an error.
Python file write() function
The file write() function writes a sequence of strings to the file. If the file has already content in there, then it will overwrite it.
# app.py mainFile = 'add.txt' file = open(mainFile, 'w') file.write('AppDividend welcomes Python Language \n')
Now, we can also append the content to the file and not overwrite that content by the following code.
# app.py mainFile = 'add.txt' file = open(mainFile, 'a') file.write('Hakuna Matata \n')
Due to a flag, it will append the content after the existing content. It does not overwrite the content.
Create a new file in Python
We can also create a new file in Python. Let us see the following code.
# app.py mainFile = 'new.txt' file = open(mainFile, 'x')
The above code will create a new empty file called new.txt.
How to Close the file in Python
After performing the file operations, we can close that file by calling the close() function on that file.
# app.py mainFile = 'new.txt' file = open(mainFile, 'x') file.write('Hakuna Matata \n') file.close()
The above code will create a new file called new.txt and add the content inside it and then write the content inside that file and close that file.
Python File Handling Methods
|detach()||Separate an underlying binary buffer from the TextIOBase and return it.|
|fileno()||Return the integer number (file descriptor) of the file.|
|flush()||Flush a write buffer of the file stream.|
|isatty()||Return True if a file stream is interactive.|
|read(n)||Read almost n characters from the file. Reads till the end of the file if it is negative or None.|
|readable()||Returns True if a file stream can be read from.|
|readline(n=-1)||Read and return one line from a file. Reads in at most n bytes if specified.|
|readlines(n=-1)||Read and return the list of lines from the file. Reads in at most n bytes/characters if specified.|
|seek(offset,from=SEEK_SET)||Change the file position to offset bytes, in reference to from (start, current, end).|
|seekable()||Returns True if the file stream supports random access.|
|tell()||Returns the location of the current file.|
|truncate(size=None)||Resize the file stream to size bytes. If the size is not specified, resize them to the current location.|
|writable()||Returns True if the file stream can be written to.|
|write(s)||Write strings to the file and return the number of characters written.|
|writelines(lines)||Write a list of the lines to a file.|
Finally, File Handling In Python example is over.