【python】如何在指定目录创建文件夹与文本

在日常爬取数据的过程中,经常会碰到要保存信息的情况,如保存为txt文本,有时大量文件的保存还需要统一目录到某个文件夹,使用的频率很高,在此做点小总结。

创建文件

推荐使用open方法:

#写法一:
f = open('result.txt','w+',encoding='utf-8')
with f:
    f.write(data)
f.close()

#写法二:
with open('result.txt','w+',encoding='utf-8')as f:
    f.write(data)
f.close()

open方法中的w+这个参数就相当于验证了一下result.txt这个文件在当前目录下是否存在,如果不存在则在当前目录创建该文件,代码效果如下:

import os
file = "result.txt"
if not os.path.exists(file):
    os.mknod(file)

两种写法可以根据具体场景具体变更使用,当文本量较小,主要在于创建该文本的情况下,可以使用os的mknode或者open的写法一第一行,如果是文本内容写入与创建一起用的话,用open方法更适合一点,可以省几行代码表示同一意思。

 

创建文件夹

关于创建文件夹,os模块中有两个方法都是用来创建文件夹的,但是两者有细微的区别,经常容易让人混淆,一个是mkdir()方法,一个是makedirs()方法。

推荐使用os.makedirs()方法:

import os
path = 'D:\\not_exist_dir\\not_exist_childir'
if not os.path.exists(path):
    os.makedirs(path)

推荐makedirs的方法的原因在于如果判断文件夹与文件夹的父目录也不存在时,该方法会将两个目录都创建,而不会像mkdir方法报错,mkdir方法要求父目录也要存在,相当于如下语句:

import os
par_path = 'D:\\not_exist_dir'
path = 'D:\\not_exist_dir\\not_exist_childir'
if not os.path.exists(par_path):
    os.mkdir(par_path)
if not os.path.exists(path):
    os.mkdir(path)

 

发布了22 篇原创文章 · 获赞 3 · 访问量 1894

猜你喜欢

转载自blog.csdn.net/weixin_44322399/article/details/103488331
今日推荐