首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何打开(读-写)或创建允许截断的文件?

如何打开(读-写)或创建允许截断的文件?
EN

Stack Overflow用户
提问于 2012-04-27 11:27:13
回答 4查看 46.1K关注 0票数 40

我想:

  • 如果文件存在,则以读写模式打开它;
  • 如果它不存在,就创造它;
  • 在任何时间-任何地点都可以截断它。

编辑:使用截断,我的意思是写到一个位置,并丢弃文件的其余部分(如果有)

所有这些都是原子性的(使用单个open()调用或模拟单个open()调用)

似乎没有一种开放的模式适用于:

  • R:显然不起作用;
  • 如果文件不存在,r+:失败;
  • w:如果文件存在,请重新创建该文件;
  • w+:如果文件存在,就重新创建它;
  • 答:不识字;
  • a+:不能截断。

我尝试过的一些组合(rw、rw+、r+w等)似乎也不起作用。有可能吗?

Ruby的一些文档 (也适用于python ):

代码语言:javascript
复制
r
Read-only mode. The file pointer is placed at the beginning of the file.
This is the default mode.

r+
Read-write mode. The file pointer will be at the beginning of the file.

w
Write-only mode. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.

w+
Read-write mode. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.

a
Write-only mode. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.

a+
Read and write mode. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
EN

Stack Overflow用户

回答已采纳

发布于 2012-04-27 14:10:44

根据OpenGroup

O_TRUNC 如果文件存在并且是一个常规文件,并且该文件被成功地打开了O_RDWR或O_WRONLY,那么它的长度将被截断为0,并且模式和所有者保持不变。它不会对FIFO特殊文件或终端设备文件产生影响。它对其他文件类型的影响取决于实现。将O_TRUNC与O_RDONLY结合使用的结果是未知的。

因此,当打开带有"w“或"w+”的文件时,可能会传递w+。这给了“截断”一个不同的含义,而不是我想要的。

对于python,该解决方案似乎使用os.open()函数在低级别的I/O上打开文件。

以下python函数:

代码语言:javascript
复制
def touchopen(filename, *args, **kwargs):
    # Open the file in R/W and create if it doesn't exist. *Don't* pass O_TRUNC
    fd = os.open(filename, os.O_RDWR | os.O_CREAT)

    # Encapsulate the low-level file descriptor in a python file object
    return os.fdopen(fd, *args, **kwargs)

有我想要的行为。您可以这样使用它(实际上,它是我的用例):

代码语言:javascript
复制
# Open an existing file or create if it doesn't exist
with touchopen("./tool.run", "r+") as doing_fd:

    # Acquire a non-blocking exclusive lock
    fcntl.lockf(doing_fd, fcntl.LOCK_EX)

    # Read a previous value if present
    previous_value = doing_fd.read()
    print previous_value 

    # Write the new value and truncate
    doing_fd.seek(0)
    doing_fd.write("new value")
    doing_fd.truncate()
票数 33
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10349781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档