python file seek skips lines

自古美人都是妖i 提交于 2019-12-10 20:26:49

问题


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:

  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.



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!