Home » Python

Python File write() Method with Example

Python File write() Method: Here, we are going to learn about the write() method, how to write text in a file in Python programming language?
Submitted by IncludeHelp, on December 17, 2019

File write() Method

write() method is an inbuilt method in Python, it is used to write the content in the file.

Syntax:

    file_object.write(text/bytes)

Parameter(s):

  • text/bytes – Specifies the text to be written in the file.

Return value:

The return type of this method is <class 'int'>, it returns the total number of the written in the file.

Example:

# Python File write() Method with Example

# creating a file 
myfile = open("hello.txt", "w")

# writing to the file
res = myfile.write("Hello friends, how are you?")
print(res, "bytes written to the file.")
# closing the file
myfile.close()

# reading content from the file
myfile = open("hello.txt", "r")
print("file content is...")
print(myfile.read())
myfile.close();

# writing more content to the file
# opening file in append mode
myfile = open("hello.txt", "a")

# writing to the file
res = myfile.write("Hey, I am good!")
print(res, "bytes written to the file.")
# closing the file
myfile.close()

# reading content from the file again
myfile = open("hello.txt", "r")
print("file content is...")
print(myfile.read())
myfile.close()

Output

27 bytes written to the file.
file content is...
Hello friends, how are you?
15 bytes written to the file.file content is...
Hello friends, how are you?Hey, I am good!





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





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.