TEXT FILE MANIPULATION IN PYTHON
There are four ways that we manipulate a file in general.
- read
- write
- append
- delete
In python, text file can be manipulated in similar way.
There are options which can be used with open() function which opens a file and return the contents of the file or insert data based on the options specified inside.
r - read
w - write
a - append
There is no direct way to delete a string from a text file. But the string the updated using append mode and
#Write the file
f = open("Colour.txt","w")
f.write("Red\n")
f.write("Green\n")
f.write("Blue\n")
f.close()
#Read the file
f = open("Colour.txt","r")
print(f.read())
#Add new entries to existing file
f = open("Colour.txt","a")
f.write("Yellow\n")
f.close()
#Read the file
print('*'*40)
f = open("Colour.txt","r")
print(f.read())