**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_path
the 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 . new
We then use the variable to specify the path to the file file_path
to create , concatenating the folder path and file name using .ddd.txt
f-string
Next, we os.makedirs()
created new
the folder using the function. exist_ok=True
Parameter means that if the folder already exists, no exception will be thrown.
We then use with open(file_path, "w") as file
open to open ddd.txt
the file and "w"
open it in write mode. In with
the statement block, we use file.write(content)
to write the specified string content
to 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 new
folder named under the current folder, create a ddd.txt
file named inside it, and write the specified string to the file.