Skip to content

File Handling in Python






Python write files





How to write an existing file in python file handling ?


We can write an existing file with the help of append mode (“a”). Append mode will append the new line to the end of the file. 


Text File : We have a text file named test_file_2.txt

Hello !
Welcome to the Codifyshow !!
The file name is test_file_2.txt
Thanks!

Example :

# Open the test_file_2 and append the new line with the help of "a" mode.
fs=open("test_file_2", "a")
fs.write("We can add one more line !")
fs.close()

# After appending, again open the file in read mode.
fs=open("test_file_2", "r")
print(fs.read())


Output :

Hello !
Welcome to the Codifyshow !!
The file name is test_file_2.txt
Thanks!We can add one more line !





How to overwrite an text file in file handling?


We can overwrite the text file with the help of write mode (“w”) . write mode overwrites the entire content of the file.


Example :

# Open the test_file_2 in the write mode and overwrites the content
fs=open("test_file_2", "w")
fs.write("we have deleted the entire content !")
fs.close()

# After writing, again open the file in read mode
fs=open("test_file_2", "r")
print(fs.read())


Output :

we have deleted the entire content !





How to create a new file in python file handling?


You can create a text file in two ways :


Example 1 : Create a new and empty text file by using “x” mode.

fs = open("my_new_file.txt", "x")

A new and empty text file has been created named “my_new_file”.






Example 2 : Create a new file if do not exist by using the “w” mode.

fs = open("my_new_file_1.txt", "w")

A new file has been created named “my_new_file_1”.