In Python, handling files is basic and simple. we will describe read and write files in Python.
We must first open a file before we can read from or write to it. When we’re finished, it needs to be closed so that the file’s resources may be released.
As a result, a file operation in Python is performed in the following order:
- Create a new file
- Read or write
- Close the document.
Table of Contents
Open a file in python
To open a file in Python, use the open() function. This function returns a file object, often known as a handle, which can be used to read or change the file.
## read and write files in Python # open file f = open("file_name.txt") # specifying full path f = open("path/to/file.ext") ##
When we open a file, we can define the read, write or append mode. We specify whether we want to read “
r “, write ”
w “, or append “
a ” to the file with the mode parameter.
We can additionally specify whether the file should be opened in a text or binary form.
Reading in text mode is the default setting. Reading from the file in this mode, we get strings.
Binary mode, on the other hand, returns bytes and is the mode to use when working with non-text files such as images or executable files.
Modes for file handling in python
|Opens a file and appends it to the end of it without truncating it. If the file does not exist, it is created.|
|This program runs in binary mode.|
Closing Files in Python
We must correctly close the file once we have finished performing actions on it.
When you close a file, the resources associated with it are released. The
close() function in Python is used to do this.
## read and write files in Python f = open("test.txt", 'r') # ... different file operations here ... # closing the file f.close() ##
We can ensure that the file is properly closed even if an exception is generated, causing process flow to halt.
with statement is the most effective technique to close a file. When the block inside the
with statement is exited, the file will be closed.
close() method does not need to be called manually. Internally, it is carried out.
## read and write files in Python with open("file_name.txt", 'r') as f: # perform file operations here ##
Writing to Files in Python
In Python, we need to open the file in write
a, or exclusive creation
x mode in order to write into it.
We must be cautious while using the
w mode because it will overwrite a file that already exists. As a result, all previous data is deleted.
write() method is used to write a string or a sequence of bytes. The number of characters written to the file is returned by this method.
## read and write files in Python with open("file_name.txt", 'w') as f: f.write("My first txt file in using python\n") ##
If file_name.txt does not already exist in the current directory, this application will create it. If it exists, it has been overwritten.
Reading Files in Python
We must open a file reading ”
r ” mode in Python to read it.
This can be accomplished using a variety of approaches. To read in the size number of data, we can use the read(size) method. It reads and returns up to the end of the file if the size option is not given.
The text.txt file we created in the previous step can be read in the following way:
## read and write files in Python f = open("file_name.txt",'r') # read the first 4 data f.read(5) # read the next 4 data f.read(5) # read till end of file f.read() ##
We can also read individual lines from a file using the
readline() method. This method reads a file until it reaches the newline character, which includes the newline character.
## read and write files in Python f.readline() 'This is my first line in text file.\n' ##
readlines() method produces a list of the file’s remaining lines. When the end of the file is reached, all of these reading methods return empty results.
## read and write files in Python f.readlines() ['This is my first line in text file\n', 'This is second line\n', 'The line number three\n'] ##
Python File Methods
In Python, there are a number of file methods. The following are a few of them.
|close()||Closes a file that has been opened. If the file is already closed, it has no effect.|
|detach()||Returns the underlying binary buffer after separating it from the TextIOBase.|
|fileno()||Returns the file’s integer descriptor (file number).|
|flush()||Flushes the file stream’s write buffer.|
|isatty()||If the file stream is interactive, this method returns True.|
|read(n)||The maximum number of characters read from the file is n. If the value is negative or None, it reads until the end of the file.|
|readable()||If the file stream can be read, this method returns True.|
|readline(n=-1)||Reads one line from the file and returns it. If n is supplied, it reads in at most n bytes.|
|readlines(n=-1)||Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.|
|seek(offset,from=||Reads the file and returns a list of lines. If n is given, it reads in at most n bytes/characters.|
|seekable()||If the file stream supports random access, this method returns True.|
|tell()||Returns a number that represents the file’s object’s current position.|
|truncate(size=||The file stream is resized to size bytes. If no size is supplied, it will resize to the current location.|
|writable()||Returns If the file stream can be written to, this value is true.|
|write(s)||Returns the number of characters written after writing the string s to the file.|
|writelines(lines)||A list of lines is written to the file.|
Read more: How to create a QR code in python?