python的几个小实现

1、递归遍历文件:

import os
import string
import shutil
from stat import ST_CTIME, ST_MTIME

def getFileNames(sPath):
for file in os.listdir(sPath):
os.chdir(sPath)
if os.path.isdir(file) is True:
print file
cur = sPath + '\\'
getFileNames(cur+ file)
else:
print file 
  
if __name__ == '__main__':
sPath = r'C:\Documents and Settings\Administrator\My Documents\Downloads'
getFileNames(sPath)
os.system('pause')

2、移动文件:

import os
import string
import shutil
from stat import ST_CTIME, ST_MTIME


def getFileNames():
sPath = r'C:\Documents and Settings\Administrator\My Documents\Downloads'
sToPath = r'E:\weiquanluo'
os.chdir(sPath)
print("start moving")
for root, dirs, files in os.walk(sPath):
  for filename in files:
  print filename
  path=os.path.join(root,filename)
  shutil.copyfile(path,os.path.join(sToPath,filename))
 
print "finish moving"
  
if __name__ == '__main__':
getFileNames()
os.system('pause')

3、改变文件名:

import os
import string
sPath = 'E:\\weiquanluo'
sFileNames = os.listdir(sPath)
print("start changing")
for FileName in sFileNames:
TmpName = FileName.split('_');
sNewFileName = sPath + "\\PlyNAM_" + TmpName[1]
print sPath
print sNewFileName
os.rename(sPath + "\\"+ FileName, sNewFileName)
print "finish changing"
os.system('pause')

4、1和2组合即可移动或复制整个文件夹的内容

你可能感兴趣的:(python的几个小实现)