EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • 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 Python File Methods
 

Python File Methods

Priya Pedamkar
Article byPriya Pedamkar

Updated March 20, 2023

Python File Methods

 

 

Introduction to Python File Methods

File methods are the methods used for manipulating the files and the contents of files in any specific system. In python, there are specific pre-defined methods for working on the files and contents, such as open(), read(), readline(), next(), write(), writelines(), truncate(), seek() and close(). Open(), as the name says, used for open function, which along with other parameters like r, w, a, etc., expands the scope further. Similarly, write() can be combined with few parameters like r, a and w.

Python File Methods and File Objects

A file object is a way to access, use and manipulate user-accessible files. Let’s discuss some methods first to read files:

1. Open()

This function facilitates the user to open a file from a particular location and with a specific access mode.

Syntax:

open(address,access_mode)

“address” is your local system address where the file resides, and access mode is like: read-only, write-only, read and write both, etc.

List of All Modes:

  • r: This mode opens a file in read-only form
  • w: This mode opens a file in the write-only form
  • r+: This mode opens a file in both reads and writes form
  • w+: This mode opens a file in both write and read
  • a: This mode opens a file for appending purpose
  • a+: This mode opens a file for both appending as well as for reading

Example:

eg1

2. Read()

This function facilitates reading the full file in the form of a string. However, one can restrict the reading to a certain limit by specifying the size in this function like read(size).

Example:

Let’s see example through small code,

f = open("C:/Users/Test/desktop/Hello.txt", "r")
print(f.read())
ff = open("C:/Users/Test/desktop/Hello.txt", "r")
print(ff.read(5))

Output:

eg2.1

eg2.2

3. Readline()

This helps the user reading only the first line of the file or reading line until it meets an EOF character in the file. Suppose EOF is met at first, then an empty string will be returned.

Example:

f = open("C:/Users/Test/desktop/Hello.txt", "r")
print(f.read())
ff = open("C:/Users/Test/desktop/Hello.txt", "r")
print(ff.readline())

Output:

Python File Methods eg3.1

Python File Methods eg3.2

As one can see, out of all three lines present in the file, the readline has printed only the first line.

4. Next()

file.next is helpful while iterating a file through a loop. Every time it’s been called, it takes the next line.

Example:

Our file “Hello.txt” has 3 lines shown below,

Python File Methods eg4

Code:

ff = open("C:/Users/Test/desktop/Hello.txt", "r")
print(ff.next())
print(ff.next())

Output:

Python File Methods eg4.1

5. Write()

file.write() function is used to write the content in the output file.

Example:

Python File Methods eg5

As one can notice, a parameter is specified, i.e. “a”. Here it means append to the content to this file. If the file exists, it will write further. If the file doesn’t exist, it will be created and then written. These three types of parameters that can be used here:

  • “x”: This is for creating a file. If the file exists with that name, an error will be thrown.
  • “a”: This is for appending. If a file doesn’t exist, it will create that file.
  • “w”: This will create that file if the file doesn’t exist and then write to it.

6. writelines()

Like the way readlines used to read string line by line, in iteration form. Similar way writelines is used to write string line if that’s in an iterable object form.

Code:

f = open("sample_EDUCBA.txt","w+")
iter_seq = ["This is good platform\n", "Datascience is buzzword"]
line = f.writelines( iter_seq )
f.close()

Output:

In the python console,Python File Methods eg5.1

The generated file is,

python generated file

7. truncate()

As the name suggests, this helps you shorten the file by chopping it off from anywhere required by the user.

Example: We have an input file,

python input file

Code:

ff = open("C:/Users/Test/desktop/sample_EDUCBA.txt", "r+")
print(ff.read())
ff = open("C:/Users/Test/desktop/sample_EDUCBA.txt", "w+")
ff.truncate()
ff = open("C:/Users/Test/desktop/sample_EDUCBA.txt", "r+")
print(ff.read())

Output:

Step1:

Python File Methods eg7

Step 2:

eg7.1

As one can notice, after getting truncated, there nothing printed on the console.

8. Seek()

This function helps users to set the offset position. By default, the value is 0. This is very useful when someone wants to adjust the position of the reading and writing pointer.

Example:

ff = open("C:/Users/i505860/sample_EDUCBA.txt", "r+")
ff.seek(0)
print(ff.readline())
ff = open("C:/Users/i505860/sample_EDUCBA.txt", "r+")
ff.seek(3)
print(ff.readline())

Output:

Step1:

eg8

Step2:

 eg8.1

9. Close()

This function closes the file. A file, once it gets closed, can no more be used for reading or writing. File object created in reference to one file gets automatically closed when the same file object is assigned with another file; in python, it’s always good to close the file after use. A close function might throw an error in some situations where one running out of disk space.

Example:

f = open("sample_EDUCBA.txt","w+")
iter_seq1 = ["This is good platform\n", "Datascience is buzzword"]
line = f.writelines( iter_seq1 )
f.close()
iter_seq2 = ["Analytics Insights\n", "Machine Learning"]
f.writelines( iter_seq2 )

Output:

eg9

As one can notice, file object got created and written with some lines like:

“This is good platform\n”, “Data science is the buzzword.”
The file then closed. However, we tried writing a few more sentences like:
“Analytics Insights\n”, “Machine Learning”
Which resulted in “ValueError”.

Conclusion

The above-covered functions are important and easy to use functions in file handling with python. They are easy to grasp and use in a python programming language. Keeping these nitty-gritty functions handy is always a good practice while writing production-level code. Beginners can get a good grip over these by practicing them all.

Recommended Articles

This is a guide to Python File Methods. Here we discuss different python file methods along with the examples and their implementation. You may also look at the following articles to learn more –

  1. List Comprehensions Python
  2. Socket Programming in Python
  3. Inheritance in Python
  4. File Handling in Java

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
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
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 Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW