Python opens a file with open, if there is no such file, it will be created automatically

When you open a file using Python's open()function, it automatically creates a new file if it doesn't exist.

For example, the code below tries to open a file called "new_file.txt". If the file does not exist, open()the function will create a new file.

file_path = "new_file.txt"

with open(file_path, "w") as file:
    file.write("This is a new file.")
    # 这里可以执行其他文件操作

In the above code, open(file_path, "w")when opening a file with , if the file "new_file.txt" does not exist, a new empty file will be created automatically. Then, we file.write()write to the file using the method.

It is important to note that before writing to the file, you need to ensure that you have appropriate file access permissions and that the target folder exists. Otherwise, an exception may be thrown. The destination folder can be created with appropriate code before the file operation, for example using os.makedirs()the function to create a folder.

Guess you like

Origin blog.csdn.net/m0_66238629/article/details/131616357