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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.