创建一个不存在的文件

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

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

332147 次浏览

我觉得这样应该行得通:

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

首先,在 Python 中没有 !运算符,那就是 not。但是 open也不会无声无息地失败——它会抛出一个异常。块需要正确缩进—— Python 使用空格来表示块包含。

因此我们得到:

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

Using input() implies Python 3, recent Python 3 versions have made the IOError exception deprecated (it is now an alias for OSError). So assuming you are using Python 3.3 or later:

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

First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition. You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.

也就是说,你可以按照 That One Random 矬子的建议来做,使用 try: 。实际上,根据蟒蛇的座右铭“请求原谅比请求许可更容易”,这就是提议的方式。

但是,你也可以很容易地测试是否存在:

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

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

import os


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

更新 :

正如 Cory Klein所提到的,在 Mac OS 上使用 os.mknod()需要一个 root 权限,所以如果您是 Mac OS 用户,您可以使用 > open () < a href = “ https://docs.python.org/3/library/function tions.html # open”rel = “ noReferrer”> 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()

I hope this helps. [FYI am using python version 3.6.2]

请注意,每次用这种方法打开文件时,文件中的旧数据都会被销毁,而不管是“ w +”还是仅仅“ w”。

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

这里有一个快速的两行程序,我使用它来快速创建一个文件,如果它不存在。

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

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

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

if the folder location is also unknown

try using

pathlib.Path.mkdir