Write Text File in Python

Write Text File in Python programming by using fopen() os library function to write any text file by using mode 'w' to write text in text file.

Program Renaming Text File

Program

import os #importing 'os' library for working with Files.
#Rename a file from 'MyTxtFile.txt' to 'MyTxtFile2.txt'.
os.rename("C://test/MyTxtFile.txt", "C://test/MyTxtFile2.txt")
print("MyTxtFile text file name is changed to MyTxtFile2 in C directory")
Output
MyTxtFile text file name is changed to MyTxtFile2 in C directory

Program Writing Text in Text File

Program

fobj = open("C://MyTxtFile.txt", 'w') #opening File.
fobj.write("HiLaLs\n") #writing Text in
fobj.write("Khan\n") #Text File and '\n'
fobj.write("Afridi") #used for New Line.
fobj.close() #closing Opened File.
print("All text is write in MyTxtFile text file")
Output
All text is write in MyTxtFile text file

Program Writing Lines of Text in Text File

Program

fh = open("C://MyTxtFile.txt", "w")
lines_of_text = ["a line of text\n", "another line of text\n", "a third line"]
fh.writelines(lines_of_text) #writing 'lines_of_text' values in File.
print("Text is write in MyTxtFile text file")
Output
Text is write in MyTxtFile text file

Program Appending Text in Text File
Program

fh = open("C://MyTxtFile.txt", "a") #opening File.
fh.write("\nHello World again\n") #writing Text
fh.write("Good By World") #in Text File.
fh.close #closing Text File.
print("Write Successfully!")
Output
Write Successfully!