File Write in Python

Append (a ) : Add data at the end of the file. Existing data retained
Write ( w) : Add data at the beginning of the file. Existing data overwritten

Create a file and Write to it

If any existing file is there , it will be overwritten. A new file will be created.
fob=open('data1.txt','w')
fob.write("this is a new text just written")
fob.close()
If we don't want any existing file to be overwritten then we need to change the mode of opening of the file.
fob=open('data1.txt','x')
fob.write("this is a new text just written")
fob.close()
Above code will give error as data1.txt file is already there.

Let us write and then read the content.
fob=open('data1.txt','w')
fob.write("this is a new text just written")
## Writting over , now read
fob=open('data1.txt','r')
print(fob.read())
fob.close()
Output is here
this is a new text just written
path="D:\\testing\\canonical\\my_file.txt"

fob= open(path,'r',encoding='utf8',errors='ignore')
data=fob.read() # collect data 

data=data.replace('abc','jkl',1)
with open(path, 'w') as file:
    file.write(data)code>

Example 1: Writing Multiple Lines to a File

with open('data2.txt', 'w') as f:
    lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
    f.writelines(lines)
    
with open('data2.txt', 'r') as f:
    print(f.read())  # Output: Line 1\nLine 2\nLine 3\n
Output:
Line 1
Line 2
Line 3

Example 2: Writing Binary Data

with open('binary_file.bin', 'wb') as f:
    f.write(b'Binary data here')

Example 3: Writing to a File in Append Mode

with open('data2.txt', 'a') as f:
    f.write("This is an appended line.\n")
    
with open('data2.txt', 'r') as f:
    print(f.read())  # Output will include the appended line at the end.
Output:
This is an appended line.

Example 4: Writing User Input to a File

with open('user_data.txt', 'w') as f:
    user_input = input("Enter some text: ")
    f.write(user_input)

File Read File Append


Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer