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.
        
            By IncludeHelp Last updated : November 26, 2023
        
    
    
    File write() Method
    The write() method is an inbuilt method in Python, it is used to write the content in the file.
    
    Syntax
    The syntax of the write() method is:
file_object.write(text/bytes)
    Parameter(s)
    The parameter(s) of the write() method is/are:
    
        - 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.
    
    write() Method: 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
    The output of the above example is:
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!
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement