以下是 Python 代码实现:

import os

# 新建文件路径
file_path = r'D:\test\test7.txt'

# 判断文件夹是否存在,如果不存在则创建文件夹
if not os.path.exists(os.path.dirname(file_path)):
    os.makedirs(os.path.dirname(file_path))

# 写入汉字到文件中
with open(file_path, 'w', encoding='utf-8') as f:
    f.write('全部汉字')

在这个代码中,首先定义了文件路径 'file_path',然后通过 'os.path.exists()' 函数判断 'D:\test' 文件夹是否存在,如果不存在则用 'os.makedirs()' 函数创建文件夹。然后用 'open()' 函数打开文件并写入汉字,最后使用 'with' 语句自动关闭文件。

Python 创建文件并写入汉字 - D 盘 test 目录下的 test7.txt

原文地址: http://www.cveoy.top/t/topic/osAe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录