在Python中,如何打开一个文件进行写入,但如果文件不存在则不创建?

In Python, how to open a file for writing, but do not create it if the file does not exist?

文件是/dev下的设备。我不想把事情搞砸,所以如果文件不存在,我不应该创建它。如何在 Python 中处理此问题?

希望用open方法解决这个问题。也就是说,当文件不存在时,它应该抛出类似 mode "r" 的 IOError。不要将问题重定向到 "check if a file exists".

import os

if os.path.exists(dev):
    fd = os.open(dev, os.O_WRONLY) # or open(dev, 'wb+')
    ...

同时勾选 How to perform low level I/O on Linux device file in Python?

有两种方法可以做到这一点。

from os.path import exists
if exists(my_file_path):
    my_file = open(my_file_path, 'w+')

如果你需要根据现有的文件触发东西,那是最好的方法。

否则就open(file_path, 'r+')

这是一个简单的 python 脚本,它显示目录中的文件、文件所在的位置以及真实文件是否存在

import os

def get_file_existency(filename, directory):
 path = os.path.join(directory, filename)
 realpath = os.path.realpath(path)
 exists = os.path.exists(path)
 if exists:
   file = open(realpath, 'w')
 else:
   file = open(realpath, 'r')