如果文件不存在,请创建一个文件

Mig*_*dez 46 python createfile

我需要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")
Run Code Online (Sandbox Code Playgroud)

错误消息表明该行存在问题if(!fh).我可以exist在Perl中使用吗?

Kro*_*ron 37

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

import os

if not os.path.exists('/tmp/test'):
    os.mknod('/tmp/test')
Run Code Online (Sandbox Code Playgroud)

更新:

正如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
Run Code Online (Sandbox Code Playgroud)

  • 这会在“exists()”和“open()”之间创建竞争条件。 (4认同)
  • macOS [需要 sudo 权限才能运行 mknod](/sf/answers/2248105611/) 所以这不太可能移植到 Mac,除非你使用 `sudo` 运行你的 python 脚本。 (2认同)
  • 它在 Windows 上不起作用,操作系统没有 mknod 属性。 (2认同)

Ant*_*ala 33

好吧,首先,在Python中没有!运算符,那就是not.但是open也不会默默地失败 - 它会引发异常.并且块需要正确缩进 - Python使用空格来指示块包含.

因此我们得到:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except IOError:
    file = open(fn, 'w')
Run Code Online (Sandbox Code Playgroud)

  • 我一直在试图弄清楚为什么这比“open(fn, 'a').close()”更可取。是因为追加中的隐式“seek”可能太昂贵了吗? (2认同)

Gaj*_*mbi 23

'''
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
'''
Run Code Online (Sandbox Code Playgroud)

例:

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

我希望这有帮助.[仅供参考使用python 3.6.2版]

  • `r +`不会创建任何文件.如前所述[这里](/sf/answers/927364371/)和[这里(在说明中)](http://www.manpagez.com/man/3/fopen/)`r + `用于在读写模式下打开文件.纠正它,因为它可能会混淆人们:) (3认同)
  • 它在 Windows 上不起作用:发生异常:FileNotFoundError (3认同)

psy*_*yFi 23

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

if not os.path.exists(filename):
    open(filename, 'w').close()
Run Code Online (Sandbox Code Playgroud)

  • 简短而简洁。请删除“文件名”两边的双引号。 (2认同)
  • 不用说,在使用这个两行代码之前必须声明“import os”。 (2认同)

cda*_*rke 10

使用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')
Run Code Online (Sandbox Code Playgroud)


小智 7

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

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


Tha*_*rub 6

我认为这应该工作:

#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')
Run Code Online (Sandbox Code Playgroud)

另外,fh = open ( fh, "w")当您要打开的文件是fn

  • 好吧,那个可怜的家伙来自Perl,所以他需要他所能获得的所有帮助。 (7认同)
  • 您假设该文件不存在,因此无法打开。可能是您没有读取权限,或者文件名在某种程度上无效。裸`except`不是一个好主意。 (6认同)
  • 你不需要写一篇关于有效异常处理的论文,只需给他提供好的例子即可。还有其他答案可以做到这一点。 (2认同)