0

在python中我发现:

a=open('x', 'a+')
a.write('3333')
a.seek(2)       # move there pointer
assert a.tell() == 2  # and it works
a.write('11')   # and doesnt work
a.close()

在 x 文件中给出333311,但我们用 2 个字节偏移量进行了第二次写入,而不是 4,因此尽管文件流指针已更改,但在写入时搜索不起作用。

===> 我的问题:它是更流行语言的编程标准吗?

4

3 回答 3

1

附加模式下的文件总是将write()s 附加到文件的末尾,如您在此处看到的:

O_APPEND

如果设置,文件偏移量将在每次写入之前设置为文件末尾。

于 2013-10-30T16:30:01.133 回答
1

http://docs.python.org/2.4/lib/bltin-file-objects.html的文档:

请注意,如果打开文件进行追加(模式 'a' 或 'a+'),任何 seek() 操作都将在下一次写入时撤消。

以模式打开文件'r+',即“读写”。

于 2013-10-30T16:30:41.877 回答
0

尝试mmap。它基本上可以让您就地编辑文件。从文档:

import mmap

# write a simple example file
with open("hello.txt", "wb") as f:
    f.write("Hello Python!\n")

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print mm.readline()  # prints "Hello Python!"
    # read content via slice notation
    print mm[:5]  # prints "Hello"
    # update content using slice notation;
    # note that new content must have same size
    mm[6:] = " world!\n"
    # ... and read again using standard file methods
    mm.seek(0)
    print mm.readline()  # prints "Hello  world!"
    # close the map
    mm.close()
于 2013-10-30T16:37:57.933 回答