您的位置:宽带测速网 > 编程知识 > python怎么在指定目录创建文件

python怎么在指定目录创建文件

2025-06-14 09:02来源:互联网 [ ]

要在指定目录创建文件,可以使用Python的open()函数来创建文件并指定路径。下面是一个示例代码:

import osdirectory = "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}")

替换path/to/directory为你想要创建文件的目录路径,运行上面的代码即可在指定目录创建一个名为new_file.txt的文件,并在文件中写入Hello, world!