Python,如果存在则打开写,否则报错
Python, open for writing if exists, otherwise raise error
有没有我可以传递 open() 的选项,它会在尝试写入不存在的文件时导致 IOerror?我正在使用 python 通过 symlinks 读取和写入块设备,如果缺少 link 我想引发错误而不是创建常规文件。我知道我可以添加检查以查看文件是否存在并手动引发错误,但如果存在,我更愿意使用内置的东西。
当前代码如下所示:
device = open(device_path, 'wb', 0)
device.write(data)
device.close()
使用os.path.islink()
or os.path.isfile()
检查文件是否存在。
恐怕您无法使用 open()
函数检查文件是否存在并引发错误。
下面是open()
在python中的签名,其中name
是file_name,mode
是访问模式,buffering
指示是否在访问文件时执行缓冲。
open(name[, mode[, buffering]])
相反,您可以检查文件是否存在。
>>> import os
>>> os.path.isfile(file_name)
这将 return True
或 False
取决于文件是否存在。要专门测试一个文件,你可以使用这个。
要测试文件和目录是否都存在,您可以使用:
>>> os.path.exists(file_path)
每次都检查很麻烦,但你总是可以换行 open()
:
import os
def open_if_exists(*args, **kwargs):
if not os.path.exists(args[0]):
raise IOError('{:s} does not exist.'.format(args[0]))
f = open(*args, **kwargs)
return f
f = open_if_exists(r'file_does_not_exist.txt', 'w+')
这只是又快又脏,所以它不允许用作:with open_if_exists(...)
。
更新
缺少上下文管理器一直困扰着我,所以这里是:
import os
from contextlib import contextmanager
@contextmanager
def open_if_exists(*args, **kwargs):
if not os.path.exists(args[0]):
raise IOError('{:s} does not exist.'.format(args[0]))
f = open(*args, **kwargs)
try:
yield f
finally:
f.close()
with open_if_exists(r'file_does_not_exist.txt', 'w+') as f:
print('foo', file=f)
是的。
open(path, 'r+b')
指定"r"选项意味着该文件必须存在并且您可以阅读。
指定“+”意味着你可以写,你将被定位在最后。
https://docs.python.org/3/library/functions.html?#open
有没有我可以传递 open() 的选项,它会在尝试写入不存在的文件时导致 IOerror?我正在使用 python 通过 symlinks 读取和写入块设备,如果缺少 link 我想引发错误而不是创建常规文件。我知道我可以添加检查以查看文件是否存在并手动引发错误,但如果存在,我更愿意使用内置的东西。
当前代码如下所示:
device = open(device_path, 'wb', 0)
device.write(data)
device.close()
使用os.path.islink()
or os.path.isfile()
检查文件是否存在。
恐怕您无法使用 open()
函数检查文件是否存在并引发错误。
下面是open()
在python中的签名,其中name
是file_name,mode
是访问模式,buffering
指示是否在访问文件时执行缓冲。
open(name[, mode[, buffering]])
相反,您可以检查文件是否存在。
>>> import os
>>> os.path.isfile(file_name)
这将 return True
或 False
取决于文件是否存在。要专门测试一个文件,你可以使用这个。
要测试文件和目录是否都存在,您可以使用:
>>> os.path.exists(file_path)
每次都检查很麻烦,但你总是可以换行 open()
:
import os
def open_if_exists(*args, **kwargs):
if not os.path.exists(args[0]):
raise IOError('{:s} does not exist.'.format(args[0]))
f = open(*args, **kwargs)
return f
f = open_if_exists(r'file_does_not_exist.txt', 'w+')
这只是又快又脏,所以它不允许用作:with open_if_exists(...)
。
更新
缺少上下文管理器一直困扰着我,所以这里是:
import os
from contextlib import contextmanager
@contextmanager
def open_if_exists(*args, **kwargs):
if not os.path.exists(args[0]):
raise IOError('{:s} does not exist.'.format(args[0]))
f = open(*args, **kwargs)
try:
yield f
finally:
f.close()
with open_if_exists(r'file_does_not_exist.txt', 'w+') as f:
print('foo', file=f)
是的。
open(path, 'r+b')
指定"r"选项意味着该文件必须存在并且您可以阅读。 指定“+”意味着你可以写,你将被定位在最后。 https://docs.python.org/3/library/functions.html?#open