python-创建一个文件(如果不存在)
我需要Python的帮助。 我正在尝试打开一个文件,如果该文件不存在,则需要创建该文件并将其打开以进行写入。 到目前为止,我有:
#open file for reading
fn = input("Enter file to open: ")
fh = open(fn,'r')
# if file does not exist, create it
if (!fh)
fh = open ( fh, "w")
错误消息显示if(!fh)行上存在问题。我可以像在Perl中一样使用exist吗?
8个解决方案
35 votes
如果您不需要原子性,则可以使用os模块:
import os
if not os.path.exists('/tmp/test'):
os.mknod('/tmp/test')
更新:
正如Cory Klein所提到的,在Mac OS上使用os.mknod()必须具有root权限,因此,如果您是Mac OS用户,则可以使用open()代替os.mknod()。
import os
if not os.path.exists('/tmp/test'):
with open('/tmp/test', 'w'): pass
Kron answered 2020-07-23T16:06:46Z
32 votes
好吧,首先&