Python: Dabbling with Text Files
#Open a text file
myfile = open(‘sample.txt’)
#Reads a text file
myfile.read()
#Brings the pointer back to the beginning of the file
myfile.seek(0)
#Storing the content of the file in a variable
content = myfile.read()
print(content)
#Closing a file
myfile.close()
#Reading every line as an element
myfile.readlines()
#Updating,infact overwrites the original file
myfile = open(‘sample.txt’, ‘w+’)
Appending the file will prevent overwriting of old file
It will just append to the original file without disturbing the original
context
myfile = open(‘sample.txt’,’a+’)
Also, if the file doesn’t exist, using a+ as the argument will also create
the file.
When an argument isn’t passed, readable permission is considered
#Opens the file as a variable name and the read each line as a diffrent element in a list
with open(‘newSample.txt’, ‘r’) as mynewfile:
myvariable = mynewfile.readlines