文件目录常用函数

>>> import os
>>> print 'current dir is ', os.getcwd()           #获得当前目录
current dir is C:\Python25
>>> os.listdir(os.getcwd())                           #获得当前目录下的文件
['python-2.5.msi', 'Sys32_BackUp', 'w9xpopen.exe', 'README.txt', 'NEWS.txt', 'LICENSE.txt', 'python.exe', 'pythonw.exe', 'Lib', 'DLLs', 'include', 'libs', 'tcl', 'Tools', 'Doc', 'msvcr71.dll', 'python.exe.manifest', 'pythonw.exe.manifest', 'Scripts', 'py2exe-wininst.log', 'Removepy2exe.exe']

>>> os.mkdir('J:\\temp')                              #创建文件夹
>>> os.rmdir('J:\\temp')                              #删除文件夹
>>> os.path.isdir('J:\\vc')                             #判断是否为文件夹
True
>>> os.path.isfile('J:\\vc')                          #判断是否为文件
False
>>>

10.2.2 批量重命名

#!/usr/bin/env python
#coding=utf-8
import os
perfix = 'python'
length = 2
base = 1
format = 'mdb'
# 函数PadLeft将文件名补全到指定长度
# Str为要补全的字符
# num为要达到的长度
# padstr为达到长度说添加的字符
def PadLeft(str, num, padstr):
    stringlength = len(str)
    n = num - stringlength
    if n >= 0:
        str = padstr*n + str
    return str

# 为避免误操作,先提示用户
print 'The file in %s will be renamed' % os.getcmd()
input = raw_input('press y to continue\n')
if input != 'y':
    exit()
filenames = os.listdir(os.curdir)
# 从基数减-1, 为了使下边i=i+1在第一次执行时等于基数
i = base - 1
for filename in filenames:
    i = i+1
    # 判断当前路劲是否为文件,并且不是"rename.py"
    if filename != 'rename.py' and os.path.isfile(filename):
        name = str(i)
        name = PadLeft(name, length, '0')
        t = filename.split('.')
        m = len(t)
        if format == '':
            os.rename(filename, prefix+name+'.'+t[m-1])
        else:
            if t[m-1] == format:
                os.rename(filename, prefix+name+'.'+t[m-1])
            else:
                i = i - 1     #保证i连接
    else:
        i = i - 1             #保证i连接

10.2.3 代码框生成器

#!/usr/bin/env python
#coding=utf-8
#file: MakeCode.py
import os
import sys
import string
import datetime
# python 脚本模版
py = '''#------------------------------------------------------------
# TO:
#------------------------------------------------------------
# BY:
#------------------------------------------------------------
'''
# C模版
c = '''*------------------------------------------------------------
* TO:
*------------------------------------------------------------
* BY:
*------------------------------------------------------------
'''
if os.path.isfile(sys.argv[1]):
    print '%s already exist!' % sys.argv[1]
    sys.exit()
file = open(sys.argv[1], 'w')
today = datetime.date.today()
date = today.strftime('%Y')+'-'+today.strftime('%m')+'-'+today.strftime('%d')
filetypes = string.split(sys.argv[1], '.')
length = len(filetypes)
filetype = filetypes[length - 1]
if filetype == 'py':
    print 'use python mode'
    file.writelines('# -*- coding:utf-8 -*-')
    file.write('\n')
    file.writelines('# File: ' + sys.argv[1])
    file.write('\n')
    file.write(py)
    file.write('# Date: ' + date)
    file.write('\n')
    file.write('#------------------------------------------------------------')
elif filetype == 'c' or filetype == 'cpp':
    print 'use c mode'
    file.writelines('/*')
    file.write('\n')
    file.writelines('*------------------------------------------------------------')
    file.write('\n')
    file.writelines(' * File: ' + sys.argv[1])
    file.write('\n')
    file.write(c)
    file.write(' * Date: ' + date)
    file.write('\n')
    file.write('*------------------------------------------------------------')
    file.write('\n')
    file.write(' */ \n')
else:
    print 'just create %s' % sys.argv[1]
file.close()

 

10.2.4 遍历文件夹中的内容:

>>> import os
>>> for file in os.walk('E:\\TEST'):
... print file
...
('E:\\TEST', ['Folder'], ['AMK0824-PSG_GeminiScripts.xls', 'AMK0824.xls', 'CVS_110906-----PSG_GeminiScripts.xls', 'merlin--9CV--S-2009-140-CTUA--00.00.00------CVS_110906-PSG_GeminiScripts.xls', 'merlin--9CV--S-2009-140-CTUA--00.00.00------CVS_110906.xls'])
('E:\\TEST\\Folder', [], ['1.txt', '2.txt'])
#返回值为一个三元元组,第一个为待遍历的路径,类型为字符串;第二个为该路径中的文件夹,类型为list;第三个为该路径中的文件,类型为list。