python使用seek函数报错:io.UnsupportedOperation: can't do nonzero end-relative seeks

python使用seek(-3,2)函数报错:io.UnsupportedOperation: can't do nonzero end-relative seeks

'''当前文件目录下mytest.txt文件内容如下:
helllo,world
hahhaahh
jjjjjjj
'''

#测试seek()函数代码
fi =open("mytest.txt","r")
fi.seek(-3,2)
print(fi.read())
fi.seek(5,0)
print("第一次定位位置:",fi.tell())
print("定位后读取的文件:",fi.read())
print("读取文件后的定位:",fi.tell())
fi.close()
-------------------------
报错:
Traceback (most recent call last):
  File "D:/pythoyworkspace/file_demo/seek_Demo.py", line 3, in <module>
    fi.seek(-3,2)
io.UnsupportedOperation: can't do nonzero end-relative seeks

解决办法:fi =open("mytest.txt","rb") #将打开模式从r变成rb即可

'''mytest.txt文件内容如下:
helllo,world
hahhaahh
jjjjjjj
'''
#测试seek()函数代码
fi =open("mytest.txt","rb")  #将打开模式从r变成rb即可
fi.seek(-3,2)
print(fi.read())
fi.seek(5,0)
print("第一次定位位置:",fi.tell())
print("定位后读取的文件:",fi.read())
print("读取文件后的定位:",fi.tell())
fi.close()
-----------------------------------
b'jjj'
第一次定位位置: 5
定位后读取的文件: b'o,world\r\nhahhaahh\r\njjjjjjj'
读取文件后的定位: 31

原因分析:

这个问题主要是因为在python3和python2的问题,如果在Python2中是不会报错的,Python3则会报错。因为Pyhon3在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常


 

猜你喜欢

转载自blog.csdn.net/qq_26442553/article/details/81705050