Python Create File in Directory Guide
To create a file in a specific directory, you can use the open() function in Python to create a file and specify the path. Here is an example code:
import os
directory = "path/to/directory" # 指定目录的路径
file_name = "new_file.txt" # 新文件的名称
file_path = os.path.join(directory, file_name) # 合并目录和文件名
# 创建文件
with open(file_path, 'w') as file:
file.write("Hello, world!")
print(f"文件 {file_name} 已创建在目录 {directory}")
Replace “path/to/directory” with the directory path where you want to create the file, then run the code above to create a file named new_file.txt in the specified directory with the text “Hello, world!” written in it.