Situatie
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Let’s see the below example to clarify the difference between write mode and append mode.
Solutie
Pasi de urmat
# Python program to illustrate
# Append vs write mode
file1 = open(“myfile.txt”, “w”)
L = [“This is test1 \n”, “This is test2 \n”, “This is test3 \n”]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open(“myfile.txt”, “a”) # append mode
file1.write(“Today \n”)
file1.close()
file1 = open(“myfile.txt”, “r”)
print(“Output of Readlines after appending”)
print(file1.read())
print()
file1.close()
# Write-Overwrites
file1 = open(“myfile.txt”, “w”) # write mode
file1.write(“Tomorrow \n”)
file1.close()
file1 = open(“myfile.txt”, “r”)
print(“Output of Readlines after writing”)
print(file1.read())
print()
file1.close()
Output:
Output of Readlines after appending
This is test1
This is test2
This is test3
Today
Output of Readlines after writing
Tomorrow
Leave A Comment?