File Handling Practice Question ( DS150423 ) - 15-05-2023

Try to resolve the problem of getting the blank line, when using r+, w+, a+ modes.

1 Like
file = open("test.txt", "a+")
file.write(" girl !")             # heyyy was already present
file.seek(0)
data = file.read()     
print(data)

output : heyyy girl !

Same process goes with r+ and w+

1 Like
file = open("test.txt","r+")
file.write("Hello")
file.seek(0)
data = file.read()
print(data)
file = open("testing.txt","w+")
file.write("Hey")
file.seek(0)
data = file.read()
print(data)
file = open("testing.txt","a+")
file.write("Bye")
file.seek(0)
data = file.read()
print(data)

Screenshot (355)

1 Like

with open(“file.txt”, “r+”) as f:
content = f.read()
f.write(“New content”)

with open(“file.txt”, “w+”) as f:
f.write(“New content”)
f.seek(0)
content = f.read()

with open(“file.txt”, “a+”) as f:
f.write(“Appended content”)
f.seek(0)
content = f.read()

1 Like
file = open("newfile.txt", "w+")
file.write("jgjgjg")
file.seek(0)
gibberish = file.read()
print(gibberish)




file = open("newfile.txt", "r+")        #note file must already exist to open it in r+ mode
file.write("jgjgjg")
file.seek(0)
gibberish = file.read()
print(gibberish)






file = open("newfile.txt", "a+")
file.write("jgjgjg")
file.seek(0)
gibberish = file.read()
print(gibberish)
1 Like

@007swarajbari
Awesome :+1: