Change language

File handling in Python

| |

Python also supports file handling and allows users to handle files, ie, read and write files, and many other file handling options for working with files. The concept of file handling has extended to various other languages, but the implementation is difficult or time consuming, but like other Python concepts, this concept is also simple and short here. Python treats a file differently as text or binary, and this is important. Each line of code contains a sequence of characters, and they form a text file. Each line in a file is terminated with a special character called EOL or End of Line characters, such as a comma {,} or a newline character. It ends the current line and tells the interpreter that a new one has started. Let’s start by reading and writing files.

How the open () function works

We use the open () function in Python to open a file in read or write mode. As explained above, open () will return a file object. To return a file object, we use the open () function along with two arguments that take the file name and mode, whether read or write. So the syntax is open (filename, mode) . There are three kinds of modes that Python provides, and how to open files:

  • " P ", for reading.
  • " W ", for a letter.
  • " A ", for adding.
  • " R + ", for reading and writing

Remember that the mode argument is optional. If not passed, Python will default to " r ". Let’s take a look at this program and try to analyze how reading mode works:

# file named" geek "will be opened in read mode.

file = open ( ’geek.txt’ , ’ r ’ )

# This will print every line in the file

for each in file :

print (each)

Command open will open the file in dir reading, and the for loop will print every line present in the file.

Working in read () mode

There are several ways to read a file in Python. If you need to extract a string containing all the characters in a file, then we can use () . The complete code will work like this:

# Python code to illustrate reading mode ()

file = open ( "file.text" , "r"

print file . read ()

Another way to read the file — call a certain number of characters, as in the following code: the interpreter will read the first five characters of the stored data and return them as a string:

# Python code to illustrate read mode ()

file = open ( "file.txt" , " r " )

print file . read ( 5 )

Create a file using write () mode

Let’s see how to create a file and how write mode works:
To manipulate a file m, write the following in your Python environment:

# Python code to create the file

file = open ( ’geek.txt’ , ’ w’ )

file . write ( "This is the write command " )

file . write ( "It allows us to write in a particular file" )

file . close ()

The close () command ends all used resources and releases gives the system of that particular program.

Working in add () mode

Let’s see how add mode works:

# Python code to illustrate append () mode

file = open ( ’geek.txt’ , ’ a’ )

file . write ( "This will add this line" )

file . close ()

There are also various other commands in file processing that are used to process different x tasks such as:

 rstrip (): This function strips each line of a file off spaces from the right-hand side. lstrip (): This function strips each line of a file off spaces from the left-hand side. 

It is designed to provide cleaner syntax and exception handling when working with code. This explains why it is recommended to use them with assertion where applicable. This is useful because when using this method, all open files will be closed automatically after one is done, hence the automatic cleanup. 

# Python code to illustrate with ()

with open ( " file.txt " ) as file

data = file . read () 

# do something with the data

Using write with the () function

We we can also use the write function together with the () function:

# Pyth on illustrative code with () along with write ()

with open ( "file.txt" , "w" ) as f: 

f.write ( "Hello World !!!"

split () using file processing

We we can also split lines using Python file handling. This splits the variable when it encounters a whitespace. You can also split using any characters we want. Here is the code:

# Python code to illustrate the split () function

with open ( "file.text" , "r" ) as file :

data = file . readlines ()

for line in data:

word = line.split ()

print word

There are also various other functions that help you manipulate files and their contents. You can explore various other functions in the Python Docs.

This article contributed by Chinma Lenka . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


Common xlabel/ylabel for matplotlib subplots

12 answers


How to specify multiple return types using type-hints

12 answers


Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers


Flake8: Ignore specific warning for entire file

12 answers


glob exclude pattern

12 answers


How to avoid HTTP error 429 (Too Many Requests) python

12 answers


Python CSV error: line contains NULL byte

12 answers


csv.Error: iterator should return strings, not bytes

12 answers



Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python


How to specify multiple return types using type-hints


Printing words vertically in Python


Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries


Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically