欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python文件不存在时创建文件_python-创建一个文件(如果不存在)

发布时间:2025/10/17 python 16 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python文件不存在时创建文件_python-创建一个文件(如果不存在) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

python-创建一个文件(如果不存在)

我需要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")

错误消息显示if(!fh)行上存在问题。我可以像在Perl中一样使用exist吗?

8个解决方案

35 votes

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

Kron answered 2020-07-23T16:06:46Z

32 votes

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

这样我们得到:

fn = input('Enter file name: ')

try:

file = open(fn, 'r')

except IOError:

file = open(fn, 'w')

Antti Haapala answered 2020-07-23T16:07:11Z

20 votes

'''

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版]

Gajendra D Ambi answered 2020-07-23T16:07:35Z

10 votes

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

cdarke answered 2020-07-23T16:07:55Z

6 votes

我认为这应该工作:

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

That One Random Scrub answered 2020-07-23T16:08:22Z

1 votes

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

import os

with open("file.txt", 'w+') as f:

f.write("file is opened for business")

Clint Hart answered 2020-07-23T16:08:42Z

0 votes

首先让我提到,您可能不希望创建一个文件对象,该文件对象最终可以打开以进行读取或写入,这取决于不可复制的条件。 您需要知道可以使用,读取或写入哪些方法,这取决于您要对文件对象执行的操作。

也就是说,您可以使用try:...例外,按照“一个随机擦洗”建议的方式进行操作。 实际上,这是建议的方法,根据python的座右铭“请求宽恕比允许容易”。

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

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。

Michael S. answered 2020-07-23T16:09:16Z

-2 votes

fn = input("Enter file to open: ")

try:

fh = open(fn, "r")

except:

fh = open(fn, "w")

成功

mahdi babaee answered 2020-07-23T16:09:36Z

总结

以上是生活随笔为你收集整理的python文件不存在时创建文件_python-创建一个文件(如果不存在)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。