使用python创建空文件 [英] Create empty file using python

查看:191
本文介绍了使用python创建空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 python 创建一个路径为 x 的文件.我一直在使用 os.system(y) 其中 y = 'touch %s' % (x).我已经寻找了 os.mkdir 的非目录版本,但我找不到任何东西.有没有这样的工具可以在不打开文件的情况下创建文件,或者使用系统或弹出/子进程?

I'd like to create a file with path x using python. I've been using os.system(y) where y = 'touch %s' % (x). I've looked for a non-directory version of os.mkdir, but I haven't been able to find anything. Is there a tool like this to create a file without opening it, or using system or popen/subprocess?

推荐答案

没有打开文件是没有办法创建的os.mknod("newfile.txt")(但它需要 OSX 上的 root 权限).创建文件的系统调用实际上是带有 O_CREAT 标志的 open().所以不管怎样,你总是会打开文件.

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

因此,简单地创建文件而不截断文件(以防它存在)的最简单方法是:

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

实际上你可以省略 .close() 因为 CPython 的 refcounting GC 会在 open() 语句完成后立即关闭它 - 但这样做更干净明确地依赖于特定于 CPython 的行为也不好.

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

如果您想要 touch 的行为(即,如果文件存在,请更新 mtime):

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

您可以扩展它以在路径中创建任何不存在的目录:

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

这篇关于使用python创建空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆