Python使用os模块创建文件夹和文件

1.创建文件夹

# 导入os模块
import os

# 创建文件夹函数
def mkdir(path):
    # os.path.exists 函数判断文件夹是否存在
    folder = os.path.exists(path)

    # 判断是否存在文件夹如果不存在则创建为文件夹
    if not folder:
        # os.makedirs 传入一个path路径,生成一个递归的文件夹;如果文件夹存在,就会报错,因此创建文件夹之前,需要使用os.path.exists(path)函数判断文件夹是否存在;
        os.makedirs(path)  # makedirs 创建文件时如果路径不存在会创建这个路径
        print('文件夹创建成功:', path)

    else:
        print('文件夹已经存在:', path)


file = "D:\\python\\cache"
mkdir(file)  # 调用函数

执行下函数,查看运行结果:

 

2.创建文件

# 定义函数名:在py文件路径下创建cache的txt文件
def txt(name, text):
    # os.getcwd() 获取当前的工作路径;
    new = os.getcwd() + '\\cache\\' 
    # 判断当前路径是否存在,没有则创建new文件夹
    if not os.path.exists(new):
        os.makedirs(new)

    # 在当前py文件所在路径下的new文件中创建txt
    xxoo = new + name + '.txt'

    # 打开文件,open()函数用于打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。
    file = open(xxoo, 'w')

    # 写入内容信息
    file.write(text)

    file.close()
    print('文件创建成功', xxoo)

# 创建名称为test的txt文件,内容为hello,python
txt('test', 'hello,world')

执行下函数,查看运行结果:

 

posted on 2022-09-04 13:56  进击的qing  阅读(25241)  评论(0编辑  收藏  举报