【问题标题】:Python:How to change the position in the file from current file position? [duplicate]Python:如何从当前文件位置更改文件中的位置? [复制]
【发布时间】:2015-11-05 21:28:14
【问题描述】:

我想将文件位置从当前文件位置更改为另一个位置。假设我当前文件位置是 13,我想将此文件位置更改为 18。 我使用seek() 方法如下,但它显示了一些错误。

代码:-

fileobj = open("intro.txt","r");
content = fileobj.read(13);
pos = fileobj.tell();
print("Current position : ",pos);
fileobj.seek(5,1); #Change position from current position to next five character.

错误

fileobj.seek(5,1);

io.UnsupportedOperation: can't do nonzero cur-relative seeks

我使用 python 3.4.3。我该怎么做?

【问题讨论】:

    标签: python python-3.x file-handling


    【解决方案1】:

    您的代码在 Python 2 中有效,但在 Python 3 中无效。您必须将文件作为二进制文件打开:

    fileobj = open("intro.txt","rb");
    

    【讨论】:

    • 但是在“rb”模式下我们不能写入文件...
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2014-07-31
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    相关资源
    最近更新 更多