温馨提示×

createfile函数的用法有哪些

小亿
135
2023-07-28 20:20:12
栏目: 编程语言

createfile函数用于创建新文件,并返回一个指向该文件的文件对象。它的用法可以有以下几种:

  1. 创建一个新的空文件:

file = open(“filename.txt”, “w”)

file.close()

  1. 创建一个新的空文件,并写入内容:

file = open(“filename.txt”, “w”)

file.write(“This is the content of the file.”)

file.close()

  1. 创建一个新的文件,并将现有文件的内容复制到新文件中:

with open(“oldfile.txt”, “r”) as old_file:

with open(“newfile.txt”, “w”) as new_file:

new_file.write(old_file.read())

注意:在使用createfile函数时,要确保传递给函数的文件名是有效的并且不存在重名的文件。否则,函数可能会引发文件已存在或无效文件名的异常。

0