本篇文章给大家谈谈python中如何创建一个新文件,以及如何用python新建一个文件,希望对各位有所帮助,不要忘了收藏本站喔。

1:创建文件
# 不加路径就是当前文件夹下,如果文件夹中存在此文件,用w新建,将文件内容清零,a新建,不会清空数据
with open('****.xls', 'w', encoding='utf-8') as f:
print(f)
# 在指定文件夹下新建
with open('*:\\**文件夹\\****.xls', 'w', encoding='utf-8') as f:
print(f)
# 新建文件的时候,需要今天的时间
import datetime # 调用库
date=str(datetime.date.today()) # 新建变量
with open('*:\\**\\1.创建文件-{}.xls'.format(date), 'w', encoding='utf-8') as f:
print(f)
![]()
2:创建文件夹--不加路径就是当前文件夹下
# 单层文件夹
import os
'''os.mkdir('E:\\PY练习\\创建文件夹')如果创建的文件夹存在,程序报错,推荐先验证是否存在'''
if not os.path.exists('*:\\***\\创建文件夹'):
os.mkdir('*:\\***\\创建文件夹')
# 多层文件夹
if not os.path.exists('*:\\***\\第一层/第二层/第三层'):
os.makedirs('*:\\***\\第一层/第二层/第三层')

文章主要介绍了Python中创建新文件的方法,同时说明了创建文件夹的相关内容,包括在当前文件夹下创建单层和多层文件夹。
1万+

被折叠的 条评论
为什么被折叠?



