J Freebird
J Freebird

Reputation: 3910

python file seek skips lines

I have a file with content:

0x11111111
0x22222222
0x33333333
0x44444444

And I'm reading it line by line using:

f = open('test1', 'r')
print "Register CIP_REGS_CONTROL value:"
for i in range(4):
    content = f.read(11)
    f.seek(11, 1)
    print content

Note that there're 11 bytes each line due to the '\n' char at the end. But the output is:

0x11111111

0x33333333

There's an empty line after the 1st and 3rd line, I don't know why it's like that. If I delete the '\n' in each line, and change the size of reading and seeking to 10, I got:

0x11111111
0x33333333

2 lines are also missing. Anybody can help? Thanks in advance.

Upvotes: 3

Views: 607

Answers (3)

SiHa
SiHa

Reputation: 8411

The simplest (and safest - it ensures your file gets closed properly) way would be to use a with construct, and readline()

print "Register CIP_REGS_CONTROL value:"
with open('test1', 'r') as f:
    for i in range(4):
        print f.readline().strip()

strip() when called with no arguments removes all whitespace (which includes \n) from the beginning and end of a string.

Upvotes: 1

beetea
beetea

Reputation: 308

Two things:

  1. You don't need to seek after the read. Your position in the file will already be at the next character after the call the read.
  2. When you call print, it will add append a newline (\n) to your output.

Upvotes: 4

Elliott Frisch
Elliott Frisch

Reputation: 201439

Remove your seek call. Each call is skipping the next 11 bytes. That is read also moves the current position.

Upvotes: 5

Related Questions