EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • 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
Priya Pedamkar
Reviewed byPriya Pedamkar

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.

ADVERTISEMENT
Popular Course in this category
PYTHON for Machine Learning Course Bundle - 39 Courses in 1 | 6 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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
ADVERTISEMENT
GOLANG Course Bundle - 6 Courses in 1
23+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
iOS DEVELOPER Course Bundle - 61 Courses in 1
147+ Hours of HD Videos
61 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
JAVA SERVLET Course Bundle - 18 Courses in 1 | 6 Mock Tests
56+ Hours of HD Videos
18 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
RED HAT LINUX Course Bundle - 5 Courses in 1
28+ Hours of HD Videos
5 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - 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

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

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

*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 Login

Forgot Password?

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Extended Cyber Monday Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW