EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • All Courses
    • All Specializations
  • Blog
  • Enterprise
  • Free Courses
  • All Courses
  • All Specializations
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials File Handling Python Tutorial File Handling in Python
 

File Handling in Python

Abhilasha Chougule
Article byAbhilasha Chougule
EDUCBA
Reviewed byRavi Rathore

Updated March 27, 2023

File Handling in Python

 

 

Introduction to File Handling in Python

Python also provides support for file handling as it is one of the very important topics in all the programming languages as it is required in any of the web applications. A file is a fixed location on a disk to store some information; these are given a unique name and can be stored permanently in non-volatile memory. File handling in simple it means handling of files such as opening the file, reading, writing, and many other operations. Unlike other programming languages, Python treats files as text or binary. In this programming language, each line of the file ends with a special character known as EOL (End of the line) like comma (,) or newline character. In this article, we will see about file operations.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

How does File Handling work in Python?

Now let us start with the key function for file handling: open () function, which takes two arguments and returns the file object.

Syntax:

open (filename, mode)

Parameters:

  • Filename: As discussed earlier, when the file is created, it is given a name to locate it on the disk.
  • Mode: It specifies in which mode the file must be; this is an optional parameter because by default Python will take it as in reading mode “r”.

Types of modes used in Python

They are, to read the file we have “r” mode and result in an error if the file doesn’t exist, to write to the file we have “w” mode it will overwrite the content if already it has any content else it will create a new file if no file is present, we have “ a” mode to append the present contents to the previous contents of the file, and the last mode is “x” which is for exclusive creation of the file which creates the specific file.

Some other modes are also used like, or the combinations of the above modes are also used sometimes as modes:

  • “r+”: Which is meant for both reading a file and writing to file.
  • “t”: Text mode
  • “b”: Binary mode

Example #1

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

Output:

File Handling python - Example1

The above code is to open the file in reading mode, but it gives the error as the file does not exist.

Whenever the files are opened, and the operations are done on them, we need to close the file; else, the file will not release the resources to other files, which may lead to resource leakage, and the systems will slow down. To close the file close() function is used for the above example:

file = open("file.txt", 'r')
…..
file.close()

Now the next important operation is reading the file, which is done when we want to read the contents of the file and print it, so we use the read() function.

Example #2

file = open("file.txt", 'r')
print(file.read())

Output:

File Handling python - Example2

The above code also gives an error to as the file does not exist because it is in reading mode, so there is no such file for reading.

The next operation is writing to the file, which is done by the write() function, but here the mode will change to write mode “w”, and as usual, we need to close the file.

Example #3

file = open("file.txt", 'w')
file.write("Hello Educba")
file = open("file.txt", 'r')
print(file.read())

Output:

Hello Educba

In the above example, to write something to the file, it must be opened in write mode “w”, then only we can write to the file by using the write() function. To read these written files, we must again call the read() function on the same file in reading mode “r” then;, we can print the output as the content written into the file.

Another important operation is appending, which will write to the file without overwriting; instead, it will append the present content to the previous content. In the write mode, we have to note that if the file already exists and has some content in it and again we open it in write mode, then the file’s previous contents will be overwritten. So if we don’t want the content to be overwritten, then we need to use the append() function instead of the write() function.

Example #4

file = open("file.txt", 'w')
file.write("Hello Educba")
file.close()
file = open("file.txt", 'a')
file.write(" Training Institute")
file.close()
file = open("file.txt", 'r')
print(file.read())

Output:

Educba Training Institute

In the above example, we could see that the file which already had “Hello Educba” written to the file in write mode than when the same file was opened in append mode, then writing to the same file was just appending the content to the previous content in append mode “Training Institute” was written so the output resulted in the complete content consisting of both the contents before appending after appending mode that is “Hello Educba Training Institute”.

Conclusion

In this article, basic operations of file handling in Python have discussed in which Python allows you to read, write, append, delete, etc. We saw how the open() function is used for both creating and opening a file. Then we saw the parameters for this function which can use many different modes on files like reading “r”, write “w”, append “a”, binary “b”, text “t”, etc., and there are many different functions like read(), write(), close(), rename() renaming the files, remove() –to delete files,mkdir() –create directories in the current directory, chdir() to change the current directory, getcwd() –get the current working directory, etc.

Recommended Articles

This is a guide to File Handling in Python. Here we discuss how does File Handling work in Python along with Syntax, Parameters and respective examples. You can also go through our other related articles to learn more–

  1. Python File Methods
  2. Python Features
  3. File Handling in C++
  4. File Handling in JavaScript
Primary Sidebar
Footer
Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW