我想:

  • 以读写模式打开文件(如果存在);
  • 如果它不存在,就创造它;
  • 可以随时随地截断它.

EDIT:使用truncate,我的意思是写到某个位置,并丢弃文件的剩余部分(如果存在)

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

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

  • r:显然不行;
  • r+:如果文件不存在,则失败;
  • w:重新创建文件(如果存在);
  • w+:重新创建文件(如果存在);
  • 答:不识字;
  • a+:无法截断.

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

Ruby大约有doc个(也适用于python):

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.

推荐答案

根据OpenGroup:

O_TRUNC

如果该文件存在并且是常规文件,并且该文件已成功

因此,打开带有"w"或"w+"的文件时,可能会传递O_TRUNC.这赋予了"截断"不同的含义,而不是我想要的.

使用python,该解决方案似乎可以使用os.open()函数以低级I/O方式打开文件.

以下python函数:

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)

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

# 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()

Ruby相关问答推荐

RSpec:为什么 `instance_double` 可以与 StandardError 一起使用,但不能与其他异常类一起使用?

使用正则表达式判断用户输入的开头是否正好有两个大括号

Ruby 中的内联注释

Ruby:子字符串到一定长度,也到子字符串中的最后一个空格

Ruby |= 赋值运算符

在 Ruby 中覆盖 == 运算符

复制文件,在 Ruby 中根据需要创建目录

在 ruby​​ 中访问嵌套哈希的元素

使用 Ruby MiniTest 之前/之后的套件

查找两个数组之间的共同值

通过 x 个字符在 Ruby 中获取子字符串

判断字符串是否为空的Ruby方法?

使用 RSpec 判断某物是否是另一个对象的实例

如何传递函数而不是块

使用 RSpec 测试哈希内容

Ruby 是否有像栈、队列、链表、映射或集合这样的容器?

您的 Ruby 版本是 2.0.0,但您的 Gemfile 指定了 2.1.0

要散列的散列数组

如何从字符串创建 Ruby 日期对象?

查找与给定条件匹配的元素的索引