Python判断文件夹是否存在,不存在即创建
def make_path(p):
if os.path.exists(p): # 判断文件夹是否存在
shutil.rmtree(p) # 删除文件夹
os.mkdir(p) # 创建文件夹
localpath = '/home/user/folder'
make_path(localpath)
python之获取目录下的文件名并写入文件
背景:为了统计一个目录下所有文件名,并且写到文件中
工具:python的模块os.walk
功能:遍历目录下的所有子文件及其子文件夹,如果有子文件夹的话,会继续以子文件夹为目录递归遍历
返回:如果只有文件的话,只返回一个元组(当前目录字符串,文件夹名列表,文件名列表);如果还有文件夹的话,返回多个元组
#!/usr/bin/python
#coding=utf-8
import os
mydir = r'/home/test/'
if __name__ == '__main__':
for pathstr,dirlist,filelist in os.walk(mydir):
for file in filelist:
with open("file.txt","ab") as f:
f.write(file+'\n')
Python 中列出目录中所有文件的方法
import string, os, sys
dir = '/var'
print '----------- no sub dir'
files = os.listdir(dir)
for f in files:
print dir + os.sep + f
print '----------- all dir'
for root, dirs, files in os.walk(dir):
for name in files:
print os.path.join(root, name)
python创建文件时文件所在文件夹也不存在情况
python创建文件时文件时,其文件所在的文件夹也不存在时,通常直接创建文件难以创建成功。
在这种情况下,我们常使用的方法是先创建文件夹,然后再创建文件。
方法1:
import os
out_file = r'./gdz/dgz/ggg.py'
out_file_dir = os.path.split(out_file)[0]
print out_file_dir
if not os.path.isdir(out_file_dir):
os.makedirs(out_file_dir)
with open(out_file, 'w') as f:
f.write("hahaha")
f.close()
方法2:
import os
#先定义一个带路径的文件
filename = "/home/mydir/test.txt"
#将文件路径分割出来
file_dir = os.path.split(filename )[0]
#判断文件路径是否存在,如果不存在,则创建,此处是创建多级目录
if not os.path.isdir(file_dir):
os.makedirs(file_dir)
#然后再判断文件是否存在,如果不存在,则创建
if not os.path.exists(filename ):
os.system(r'touch %s' % filename)