繁体   English   中英

如果文件不存在则创建

[英]Create a file if it doesn't exist

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

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

如果你不需要原子性,你可以使用 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
'''
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
'''

例子:

file_name = 'my_file.txt'
f = open(file_name, 'a+')  # open file in append mode
f.write('python rules')
f.close()

我希望这有帮助。 [仅供参考,我使用的是 Python 3.6.2 版]

好吧,首先,在 Python 中没有! 运营商,那not 但是open也不会无声地失败——它会抛出异常。 并且块需要正确缩进 - Python 使用空格来表示块包含。

因此我们得到:

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

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

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

使用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')

我认为这应该有效:

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

另外,当您要打开的文件是fn时,您错误地写了fh = open ( fh, "w")

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

import os

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

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

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

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

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() 会尝试执行输入的文本。 如果您不小心想要测试文件“导入”,您会得到一个 SyntaxError。

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

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

如果文件夹位置也是未知的

尝试使用

pathlib.Path.mkdir
fn = input("Enter file to open: ")
try:
    fh = open(fn, "r")
except:
    fh = open(fn, "w")

成功

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM