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.
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>
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
with open('binary_file.bin', 'wb') as f:
f.write(b'Binary data here')
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.
with open('user_data.txt', 'w') as f:
user_input = input("Enter some text: ")
f.write(user_input)
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.