【问题标题】:how to create empty file in python [duplicate]如何在python中创建空文件[重复]
【发布时间】:2017-03-28 23:47:32
【问题描述】:

我想在 Python 中创建一个空文件。但我很难创建一个。下面是我用来创建的 Python 代码,但它给了我错误:

gdsfile  = "/home/hha/temp.gds"
if not (os.path.isfile(gdsfile)):
    os.system(touch gdsfile)

我得到的错误: 文件“/home/hha/bin/test.py”,第 29 行 os.system(触摸 gds 文件) ^ SyntaxError: 无效语法

但在命令行中,我可以使用以下命令创建新文件:touch

非常感谢您的帮助 霍华德

【问题讨论】:

  • os.system 的参数必须是字符串。这不是你现在正在传递的。此外,当您可以使用 Python 自己的 open 方法时,没有理由调用 touch 命令。

标签: python


【解决方案1】:

首先你有一个语法错误,因为os.system() 需要一个字符串参数,而你没有提供一个。这将修复您的代码:

os.system('touch {}'.format(gdsfile))

构造一个字符串并将其传递给os.system()

但更好的方法(在 Python >= 3.3 中)是简单地使用 open() 内置函数打开文件:

gdsfile  = "/home/hha/temp.gds"
try:
   open(gdsfile, 'x')
except FileExistsError:
   pass

这指定了模式x,这意味着独占创建-如果文件已经存在则操作将失败,但如果不存在则创建它。

这比使用os.path.isfile() 后跟open() 更安全,因为它避免了在检查和创建之间可能由另一个进程创建文件的潜在竞争条件。


如果您使用的是 Python 2 或更早版本的 Python 3,则可以使用 os.open() 打开带有独占标志的文件。

import os
import errno

gdsfile  = "/home/hha/temp.gds"
try:
    os.close(os.open(gdsfile, os.O_CREAT|os.O_EXCL))
except OSError as exc:
    if exc.errno != errno.EEXIST:
        raise

【讨论】:

  • 我建议在'open'前面加上'with',这样它会自动清理返回的文件句柄,例如' with open(gdsfile, 'x') as touch_file: pass'
  • ``` with open(file_name, 'a') as f: pass ```
猜你喜欢
  • 2012-09-21
  • 2018-12-10
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 2022-11-10
  • 2016-02-27
相关资源
最近更新 更多