createfile
函数可以用来创建一个新的文件,并返回一个文件对象。
首先,我们需要导入os
模块,以便使用createfile
函数。
定义createfile
函数:
import os def createfile(filename): try: file = open(filename, 'w') # 打开文件,以写入模式 file.close() # 关闭文件 print("文件创建成功") except Exception as e: print("文件创建失败:", str(e))
使用createfile
函数:
filename = "example.txt" createfile(filename)
这将在当前目录下创建一个名为example.txt
的空文件。如果文件创建成功,将输出"文件创建成功";如果文件创建失败,将输出"文件创建失败"和错误信息。
注意:在使用createfile
函数之前,请确保你具有适当的文件写入权限。