您的位置:首页 > 编程语言 > Python开发

python 文件和文件夹处理

2013-06-27 10:58 246 查看
1.os模块的常用目录处理函数

mkdir(path,[mode=0777]) 创建一个path指定的目录,mode为目录的权限设置,默认为0777(读取、写入、执行)

makedirs(name,mode=511) 创建多级目录,如'd:/path1/path2/'则在d盘中新建一个path1然后再在path1目录中新建一个path2

rmdir(path) 删除path指定的目录

removedirs(path) 删除path指定的多级目录

listdir(path) 返回path指定目录下的所有文件和目录(不包括子目录的文件)

getcwd() 返回当前的工作目录

chdir(path) 将当前的工作目录改变为path指定的目录

walk(top,topdown=True,onerror=None) 遍历目录树(返回top指定的目录中的所有文件和子目录与子目录文件)

该函数返回一个三个元素的元组,这三个元素分别是每次变量的路径名、目录列表、文件列表

topdown参数有两种True和False默认是True

True表示先返回根目录下的文件然后再返回子目录与子目录的文件

False则表示先返回子目录和子目录中的文件再返回根目录中的文件

onerror参数可以提供一个在遍历目录产生错误时处理该错误的处理函数,默认是None也就是忽略错误

2.os.path模块常用目录处理函数:

abspath(path) 返回path所在的绝对路径

dirname(path) 返回path的目录名称

exists(path) 判断path是否存在,存在返回True,反之False

getatime(filename) 返回filename的最后访问时间

getctime(filename) 返回filename的创建时间

getmtime(filename) 返回filename的最后修改时间

getsize(filename) 返回filename的大小

isabs(path) 判断path是否为绝对路径,是返回True(就算path不存在)反之False

isdir(path) 判断path是否为目录,是返回True反之False(如果path不存在也返回False哦)

isfile(path) 判断path是否问文件,是返回True反之False(如果path不存在也返回False哦)

split(path) 对path进行路径分割,返回一个以路径、非路径这个两个元素组成的元组

splitext(path) 从path中分割扩展名名称返回两个元素的元组(非扩展名名称、扩展名名称)

splitdrive(path) 从path中分割驱动器名称返回两个元素的元组(驱动器名称、非驱动器名称)

walk(top,func,arg) 遍历目录,与os.walk()功能相同

3.目录文件的遍历

在Python中有三种实现目录遍历的方法:①-递归函数、②-os.path.walk()、③-os.walk()

①-自定义递归函数进行遍历

>>> import os

>>> def VisitDir(path): #定义函数

dirlist = os.listdir(path) #使用os模块的listdir()返回目录和文件列表(不包括子目录文件)

for listname in dirlist: #遍历刚才获取得到的文件和目录列表

dirname = os.path.join(path,listname): #把当前遍历到的文件或目录名称与根目录path连接起来(也就是完整路径)

if os.path.isdir(dirname): #如果当前路径是目录

VisitDir(dirname) #使用函数递归再次处理当前路径(也就是使用本函数再次执行以上操作)

else: #如果当前路径不是目录,也就是说当前路径是一个文件

print dirname #输出完整路径的文件名称

>>>if __name__ == '__main__':

path = 'd:\code' #注意这里的路径最后最好不要有一个'\'否则Python视为新建逻辑行操作

VisitDir(path) #调用函数

d:\code\son1\1.txt #遍历成功,

d:\code\son2\2.txt

d:\code\son3\3.txt

d:\code\123.txt

后记:这个方法遍历目录的时候只能返回有文件的目录,可以在调用递归前输出一下目录就可以返回所有目录了

②-os.path.walk(top,func,art)

后记:暂缺待续

③-os.walk(top,topdown=True,onerror=None)

top参数表示需要遍历的目录树路径

topdown参数有两个选择True和False(如不提供默认为True)

当为True时则表示先遍历完了路径根目录的文件后再遍历子目录和子目录文件

当为False的时候则表示先遍历路径的子目录和子目录文件后在遍历路径根目录的文件

onerror参数的默认值是None,表示忽略遍历过程中产生的错误,如果提供参数则需提供一个处理错误的自定义函数

该函数返回一个共有三个元素的元组,三个元素分别是每次遍历的路径名称、目录列表、文件列表(注意后两个元素是列表)

#!bin/usr/python

#-*-coding:UTF-8-*-

#filename:filelist.py

import os

def VisitDir(path):

for root,sonroot,filelist in os.walk(path):

for filename in filelist:

print os.path.join(root,filename)

if __name__ == '__main__':

VisitDir(raw_input('需要遍历的目录:'))

>>>

需要遍历的目录:d:\code

d:\code\123.txt

d:\code\filelist.py

d:\code\filelist2.py

d:\code\son1\1.txt

d:\code\son2\2.txt

d:\code\son3\3.txt

>>>

文件属性程序:

#!/bin/usr/python

#-*-coding:UTF-8-*-

#filename:Fileproperties.py

import os

import time

def Show_File_Properties(path):

'''

Function_Name:Show_File_Properties(path)

显示文件的属性-包括路径、大小、创建时间、最后修改时间、最后访问时间

'''

for root,dirlist,filelist in os.walk(path):

print '路径:' + root

for filename in filelist:

state = os.stat(os.path.join(root,filename))

info = '文件名:' + filename + '\n'

info = info + '大小:' + ('%d' %state[-4]) + ' Byte\n'

t = time.strftime('%Y-%m-%d %X',time.localtime(state[-1]))

info = info + '创建时间:' + t + '\n'

t = time.strftime('%Y-%m-%d %X',time.localtime(state[-2]))

info = info + '修改时间:' + t + '\n'

t = time.strftime('%Y-%m-%d %X',time.localtime(state[-3]))

info = info + '访问时间:' + t + '\n'

print info

if __name__ == '__main__':

path = raw_input('路径:')

Show_File_Properties(path)

==================================================================

======隔断========================================================

文件的遍历、删除和添加是最常用的文件命令,利用python的系统接口,我们可以很容易的实现这些功能

# python文件处理

import os

MAX_DEPTH = 2

def traversal(path, depth):

if( MAX_DEPTH == depth):

return

else:

dirList = os.listdir(path)

for it in dirList:

if(os.path.isdir(path+'\\'+it)):

print(it)

traversal(path+'\\'+it,depth+1)

else:

print(' '*depth + it)

traversal('c:\\Program Files',1) # 遍历c:\\Program Files目录,最大深度为MAX_DEPTH

# 创建一个目录,并在目录下创建两个空文件

bFlag = True

if(bFlag):

sDir = 'c:\\python_test'

os.mkdir(sDir)

fp = open(sDir + '\\1.dat', 'w')

fp.close()

fp = open(sDir + '\\2.dat', 'w')

fp.close()

def delTree(path): # 删除目录及下面的所有文件

dirList = os.listdir(path)

for it in dirList:

if(os.path.isdir(path+'\\'+it)):

delTree(path+'\\'+it)

else:

os.remove(path+'\\'+it)

os.rmdir(path)

delTree('c:\\python_test')

======================================================

========分割符

01.#!/usr/bin/env python

02.#coding=utf-8

03.import sys, os, stat

04.def walk(path):

05.for item in os.listdir(path):

06.subpath = os.path.join(path, item)

07.mode = os.stat(subpath)[stat.ST_MODE]

08.if stat.S_ISDIR(mode):

09.if item == ".svn":

10.print "Cleaning %s " %subpath

11.print "%d deleted" % purge(subpath)

12.else: 13.walk(subpath)

14.def purge(path):

15.count = 0

16.for item in os.listdir(path):

17.subpath = os.path.join(path, item)

18.mode = os.stat(subpath)[stat.ST_MODE]

19.if stat.S_ISDIR(mode):

20.count += purge(subpath)

21.else:

22.os.chmod(subpath, stat.S_IREAD|stat.S_IWRITE)

23.os.unlink(subpath)

24.count += 1

25.os.rmdir(path)

26.count += 1

27.return count

28.if len(sys.argv) != 2:

29.print "Usage: python cleansvn.py path"

30.sys.exit(1)

31.walk(sys.argv[1])删除某目录下所有文件和文件夹:

32.Code

33.#!/usr/bin/env python

34.#coding=utf-8

35.import os

36.def delete_all_file(path):

37."delete all folers and files"

38.if os.path.isfile(path):

39.try:

40.os.remove(path)

41.except:

42.pass

43.elif os.path.isdir(path):

44.for item in os.listdir(path):

45.itemsrc = os.path.join(path, item)

46.delete_all_file(itemsrc)

47.try:

48.os.rmdir(path)

49.except:

50.pass

51.if __name__ == "__main__":

52.dirname = r'F:\trunk'

53.print delete_all_file(dirname)

==============================================

recusively delete

========

def rmtree(path, ignore_errors=False, onerror=None):

"""Recursively delete a directory tree.

If ignore_errors is set, errors are ignored; otherwise, if onerror

is set, it is called to handle the error with arguments (func,

path, exc_info) where func is os.listdir, os.remove, or os.rmdir;

path is the argument to that function that caused it to fail; and

exc_info is a tuple returned by sys.exc_info(). If ignore_errors

is false and onerror is None, an exception is raised.

"""

if ignore_errors:

def onerror(*args):

pass

elif onerror is None:

def onerror(*args):

raise

try:

if os.path.islink(path):

# symlinks to directories are forbidden, see bug #1669

raise OSError("Cannot call rmtree on a symbolic link")

except OSError:

onerror(os.path.islink, path, sys.exc_info())

# can't continue even if onerror hook returns

return

names = []

try:

names = os.listdir(path)

except os.error, err:

onerror(os.listdir, path, sys.exc_info())

for name in names:

fullname = os.path.join(path, name)

try:

mode = os.lstat(fullname).st_mode

except os.error:

mode = 0

if stat.S_ISDIR(mode):

rmtree(fullname, ignore_errors, onerror)

else:

try:

os.remove(fullname)

except os.error, err:

onerror(os.remove, fullname, sys.exc_info())

try:

os.rmdir(path)

except os.error:

onerror(os.rmdir, path, sys.exc_info())

============================

change access

====

def onerror(func, path, exc_info):

"""

Error handler for ``shutil.rmtree``.

If the error is due to an access error (read only file)

it attempts to add write permission and then retries.

If the error is for another reason it re-raises the error.

Usage : ``shutil.rmtree(path, onerror=onerror)``

"""

import stat

if not os.access(path, os.W_OK):

# Is the error an access error ?

os.chmod(path, stat.S_IWUSR)

func(path)

else:

raise

===use dos command ===

os.system('rmdir /S /Q \"{}\"'.format(directory))

=====another way=====

import os, stat, shutil

def remove_readonly(fn, path, excinfo):

if fn is os.rmdir:

os.chmod(path, stat.S_IWRITE)

os.rmdir(path)

elif fn is os.remove:

os.chmod(path, stat.S_IWRITE)

os.remove(path)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: