python写入文件时会在文件前面加上空字符

2024-10-02 04:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图保持一个文件的偏移量(文件.告诉)这样在重新启动时进程可以跳过这些字符。在

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

我复制了下面的部分。如果你能帮我弄清楚如何避免这些废品,我将不胜感激。在

非常感谢。在

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

Tags: 文件oslabmsgoffsetwritefirstc1
1条回答
网友
1楼 · 发布于 2024-10-02 04:29:36

文件中保持位置的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)介于第一次和第二次写入之间。在

相关问题 更多 >

    热门问题