Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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.

Solution 3:

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:"withopen('test1', 'r') as f:
    for i inrange(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.

Post a Comment for "Python File Seek Skips Lines"