Is there a method that, say, for example... you open a file, and usually the cursor would be at the end right? Is there a function or method that would set the cursor back to the beginning of the file?
If you want to write something at the start of a file though you would need to do something like this
#opening the file in read ("r") mode
f = open("file.txt",'r')
#get all that is in the text file so far
oldString = f.readlines()
#and close it
#delete it so we can reopen the file in write mode ('w')
#the string we are adding
newString = """
This will go
At the start"""
#writing the new string
for line in newString.split("\n"):
#writing the old string
for line in oldString:
#closing the file
That is untested code.. so im not quite sure how it will work, but hopefully it shows the concept i am trying to show :)
# exploring Python's file random access
text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
fname = 'test103.txt'
# create a test file
fout = open(fname, "w")
# open the test file for reading
fin = open(fname, "r")
# file positions are zero based
# tell the current file position
print( fin.tell() ) # 0
# read the byte at that position
print( fin.read(1) ) # A
# after reading 1 byte the position has advanced by 1
print( fin.tell() ) # 1
# read the next byte
print( fin.read(1) ) # B
print( fin.tell() ) # 2
# move the position to 10
# read the byte at position 10
print( fin.read(1) ) # K