如果文件不存在就创建一个

问题描述 投票:0回答:9

我正在尝试打开一个文件,如果该文件不存在,我需要创建它并打开它进行写入。到目前为止我有这个:

#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
吗?

python createfile
9个回答
102
投票

对于 Linux 用户。

如果你不需要原子性,你可以使用 os 模块:

import os

if not os.path.exists('/tmp/test'):
    os.mknod('/tmp/test')

macOSWindows 用户。

macOS上使用

os.mknod()
你需要root权限。 在Windows上没有
os.mknod()
方法。

因此,作为替代方案,您可以使用

open()
而不是
os.mknod()

import os

if not os.path.exists('/tmp/test'):
    with open('/tmp/test', 'w'): pass

68
投票

您可以通过

实现所需的行为
file_name = 'my_file.txt'
f = open(file_name, 'a+')  # open file in append mode
f.write('python rules')
f.close()

这些是

mode
中第二个参数
open()
的一些有效选项:

"""
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in (over)write mode
    [it overwrites the file if it already exists]
r+  open an existing file in read+write mode
a+  create file if it doesn't exist and open it in append mode
"""

39
投票

好吧,首先,在 Python 中没有

!
运算符,那就是
not
。但是
open
也不会默默地失败——它会抛出异常。并且块需要正确缩进 - Python 使用空格来指示块包含。

因此我们得到:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except IOError:
    file = open(fn, 'w')

35
投票

这是一个快速的两行代码,如果文件不存在,我会用它来快速创建文件。

if not os.path.exists(filename):
    open(filename, 'w').close()

15
投票

使用

input()
意味着 Python 3,最近的 Python 3 版本已经弃用了
IOError
异常(它现在是
OSError
的别名)。因此,假设您使用的是 Python 3.3 或更高版本:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except FileNotFoundError:
    file = open(fn, 'w')

8
投票

我认为这应该有效:

#open file for reading
fn = input("Enter file to open: ")
try:
    fh = open(fn,'r')
except:
# if file does not exist, create it
    fh = open(fn,'w')

此外,当您要打开的文件是

fh = open(fh, "w")
时,您错误地写了
fn


6
投票

请注意,每次使用此方法打开文件时,文件中的旧数据都会被破坏,无论是

'w+'
还是只是
'w'

with open("file.txt", 'w+') as f:
    f.write("file is opened for business")

1
投票

如果您知道文件夹位置并且文件名是唯一未知的东西,

open(f"{path_to_the_file}/{file_name}", "w+")

如果文件夹位置也未知

尝试使用

pathlib.Path.mkdir

0
投票

首先让我提一下,您可能不想创建一个最终可以打开以进行读取或写入的文件对象,具体取决于不可重现的条件。你需要知道可以使用哪些方法,读取或写入,这取决于你想对文件对象做什么。

就是说,您可以按照 That One Random Scrub 的建议进行操作,使用 try: ... except:。实际上,根据 python 格言“请求宽恕比许可更容易”,这是建议的方式。

但您也可以轻松测试是否存在:

import os
# open file for reading
fn = raw_input("Enter file to open: ")
if os.path.exists(fn):
    fh = open(fn, "r")
else:
    fh = open(fn, "w")

注意:使用raw_input()而不是input(),因为input()会尝试执行输入的文本。如果你不小心想测试文件“导入”,你会得到一个语法错误。

© www.soinside.com 2019 - 2024. All rights reserved.