python creates and writes files

**Question:** There is a new folder under the current folder, create a new ddd.txt file, and then write a certain string into the txt file

Method to realize:

You can use Python's file manipulation capabilities to accomplish the above tasks. Here is a sample code:

folder_path = "./new"  # new文件夹的路径
file_path = f"{
      
      folder_path}/ddd.txt"  # ddd.txt文件的路径
content = "This is the content to write into the file."

# 创建new文件夹
import os
os.makedirs(folder_path, exist_ok=True)

# 写入内容到ddd.txt文件
with open(file_path, "w", encoding='utf-8') as file:
    file.write(content)

print(f"文件 {
      
      file_path} 创建成功,并写入了内容:\n{
      
      content}")

In the above example, we first defined folder_paththe variable and specified the path of the folder to be created. Here, a relative path is used to represent the folder "./new"under the current folder . newWe then use the variable to specify the path to the file file_pathto create , concatenating the folder path and file name using .ddd.txtf-string

Next, we os.makedirs()created newthe folder using the function. exist_ok=TrueParameter means that if the folder already exists, no exception will be thrown.

We then with open(file_path, "w") as fileopen ddd.txtthe file using , and "w"open it in writing mode. In withthe statement block, we use file.write(content)to write the specified string contentto the file.

Finally, we print out a message indicating that the file was created successfully, including the file path and the content written.

When you run this code, it will create a newfolder named under the current folder, create a ddd.txtfile named inside it, and write the specified string to the file.

Guess you like

Origin blog.csdn.net/m0_66238629/article/details/131616380
Recommended