gpt4 book ai didi

写入文件的python会添加空字符

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:07 25 4
gpt4 key购买 nike

我正在尝试维护一个具有偏移值的文件 (file.tell),以便在重新启动时进程可以跳过那么多字符。

所以我有一个截断/写入/刷新的序列。但是每次它都会将空字符放在文件的顶部。该模式显示空字符的数量等于先前文件内容的长度。

我已经复制了下面的 session 。我将感谢您在弄清楚如何避免这些空值方面提供的帮助。

非常感谢。

dinesh@c1 ~/lab $ python
Python 2.6.8 (unknown, Jul 16 2013, 14:48:55)
[GCC 4.3.4 [gcc-4_3-branch revision 152973]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os,fcntl
>>> f=os.open("ha.offset", os.O_RDWR, 0744)
>>> fcntl.lockf( f, fcntl.LOCK_EX | fcntl.LOCK_NB )
>>> fd = os.fdopen(f, "w+")
>>> msg="first=123\nsecond=234\n"
>>> fd.truncate(0)
>>> fd.write(msg)
>>> fd.flush()
>>>
[1]+ Stopped python
dinesh@c1 ~/lab $ wc ha.offset
2 2 21 ha.offset
dinesh@c1 ~/lab $ fg
python
>>> msg="first=987\nsecond=9877\n"
>>> fd.truncate(0)
>>> fd.write(msg)
>>> fd.flush()
>>>
[1]+ Stopped python
dinesh@c1 ~/lab $ wc ha.offset
2 2 43 ha.offset
dinesh@c1 ~/lab $ od -c ha.offset
0000000 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
0000020 \0 \0 \0 \0 \0 f i r s t = 9 8 7 \n s
0000040 e c o n d = 9 8 7 7 \n
0000053
dinesh@c1 ~/lab $ fg
python
msg="first=1"
msg="first=1"
>>> fd.truncate(0)
>>> fd.write(msg)
>>> fd.flush()
>>>
[1]+ Stopped python
dinesh@c1 ~/lab $ !od
od -c ha.offset
0000000 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
*
0000040 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 f i r s t
0000060 = 1
0000062

最佳答案

docs for truncate声明文件中的位置被保持:

file.truncate([size])

Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.

所以我怀疑您需要在第一次和第二次写入之间的某个地方fd.seek(0)

关于写入文件的python会添加空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26900024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com