Writing Data to Text Files

Writing Data to Text Files

We can write character data to the text files by using the following 2 methods. 
  • write(str)  
  • writelines(list of lines) 

Eg:

#Follow @Programmerfect

f=open("abcd.txt",'w')
f.write("Programmerfect\n")
f.write("Richard Rahul\n")
f.write("Wolf\n")
print("Data written to the file successfully")
f.close()  

Output:

Note: In the above program, data present in the file will be overridden everytime if we run the program. Instead of overriding if we want append operation then we should open the file as follows.
  • f = open("abcd.txt","a")

Eg:

#Follow @Programmerfect

f=open("abcd.txt",'w')
list=["Programmerfect\n","Richard\n","Wolf\n","Programmer"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()  

Output:


Note: while writing data by using write() methods, compulsory we have to provide line seperator(\n),otherwise total data should be written to a single line.


 

Comments