问题
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.
回答1:
Remove your seek call. Each call is skipping the next 11 bytes. That is read also moves the current position.
回答2:
Two things:
- You don't need to
seek
after theread
. Your position in the file will already be at the next character after the call theread
. - When you call
print
, it will add append a newline (\n
) to your output.
回答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:"
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.
来源:https://stackoverflow.com/questions/24741115/python-file-seek-skips-lines