0

I am trying to learn about the functionality of the seek method. So far, I understand that seek offsets the pointer to a specific position within the file as specified by the whence statement, which defaults to 0.

  • seek(0,0) refers to the beginning of the file
  • seek(0,1) refers to the current position of the file
  • seek(0,2) refers to the end of the file
  • seek(2,2) moves the pointer 2 bytes from the current position in the file.

I have written a program that is supposed to use the seek method to write two blocks of text consecutively.

line1 = "This is line 1"
line2 = "This is line 2"
line3 = "This is line 3"

my_file = open('NewFileName.csv', 'w')

my_file.truncate()

my_file.write("%s\n%s\n%s" % (line1, line2, line3))

my_file.seek(1)

line4 = "This is new line# 1"
line5 = "This is new line# 5"
line6 = "This is new line# 6"

my_file.write("%s\n%s\n%s" % (line4, line5, line6))

my_file.close()

However, I am unable to make the program write the second block of text (line4 - line6) in a new line after the first block of text ends.

When I am trying my_file.seek(0,1) I am getting the output as

This is line 1
This is line 2
This is line 3This is new line #1
This is new line# 5
This is new line# 6

When I am trying my_file.seek(1,1), I am getting

This is line 1
This is line 2
This is line 3This is new line #1
This is new line# 5
This is new line# 6

..which appears the same as above.

Even if I writing my_file.seek(5,1), it gives the same output as above. So I am fairly confused on how the seek method actually works.

What I actually want is to have the two blocks of text write one after the another

This is line 1 This is line 2 This is line 3 This is new line# 1 This is new line# 5 This is new line# 6

Please advise where am I going wrong, or if seek is not even the right way to achieve what I want. I have read some documentation on this online, but still can't properly figure it out.

Many thanks

pb_ng
  • 361
  • 1
  • 5
  • 19
  • Do you even need to use seek? Maybe just use "write" twice. – poe123 Jul 01 '16 at 09:37
  • Also please never use integral values for constants in such cases. There are constants which make your code readable: https://docs.python.org/2/library/stdtypes.html#file.seek – poe123 Jul 01 '16 at 09:40

0 Answers0