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?

Thanks!

Recommended Answers

All 3 Replies

When you open a file, the cursor is at the beginning of the file. However

myfile.seek(0)

goes to the beginning of the file. Finally, read this.

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
f.close()


#delete it so we can reopen the file in write mode ('w')
del f
f=open("File.txt",'w')

#the string we are adding
newString = """
Hello
This will go
At the start"""

#writing the new string

for line in newString.split("\n"):
    f.write(line+'\n')

#writing the old string
for line in oldString:
    f.write(line+'\n')

#closing the file

f.close()

That is untested code.. so im not quite sure how it will work, but hopefully it shows the concept i am trying to show :)

hope it helps :)

You can easily explore it yourself ...

# exploring Python's file random access

text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

fname = 'test103.txt'

# create a test file
fout  = open(fname, "w")
fout.write(text)
fout.close()

# 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
fin.seek(10)
# read the byte at position 10
print( fin.read(1) )  # K

fin.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.