read and write files in Python

How to read and write files in Python?

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:

  1. Create a new file
  2. Read or write 
  3. Close the document.

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

Mode Description
rThe r mode opens a file for reading.
ww is used to open a file for writing. If the file does not exist, it is created, and if it does, it is truncated.
xx Creates a file for exclusive use. The operation fails if the file already exists.
aOpens a file and appends it to the end of it without truncating it. If the file does not exist, it is created.
tt Switches to text mode.
bThis 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.

The 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.

The 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 w, append 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.

The 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'
##

Finally, the 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']
##
read and write files in Python

Python File Methods

In Python, there are a number of file methods. The following are a few of them.

MethodDescription
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=SEEK_SET)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=None)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?