Home » Python

Writing, Reading content of the file in Python

In this tutorial, we are going to learn how to write content to file using write() function and how to read the content of a file using read() function in python?
Submitted by IncludeHelp, on December 27, 2018

Prerequisite: Opening, closing a file/open(), close() functions in Python

1) Writing content (using file_object.write())

To write content in a file, we use write() function, which is called with the file object name.

Syntax:

    file_object.write(data)

2) Reading content (using file_object.read())

To read the content of a file, we use read() function, which is called with the file object name.

Syntax:

    file_object.read()

It returns the content of the file in string format.

Example:

Here, we are creating a file, writing data to the file, closing the file and again reading the file in read only mode, reading the data, closing the file.

# opening a file in write mode
fo = open("data.txt","wt")

# data to write in the file
data = "Hello friends, how are you?"

# writing data to the file
fo.write(data)
# closing the file
fo.close()
print("Data is written and file closed.")

# clearing the variable 
data = ""

# opening the file in read mode
fo = open("data.txt","rt")

# reading the data and printing
data = fo.read()
print("file's content is: ")
print(data)

# closing the file 
fo.close()

Output

Data is written and file closed.
file's content is:
Hello friends, how are you? 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.