Linux 拨号vps windows公众号手机端

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

lewis 9年前 (2016-12-17) 阅读数 10 #程序编程
文章标签 python

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

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}")

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门