python-常用小程序-文件夹

1,递归遍历文件夹下所有文件

# -* - coding: UTF-8 -* -
#!/usr/bin/python


import os


path=r"D:\myapps"


#  checkFilesRec:遍历指定目录下的所有的文件(不包括文件夹)
def checkFilesRec(path):
    for root,dirs,files in os.walk(path):
        for file in files:
            print file


checkFilesRec(path)

2,不递归遍历文件夹下当前层的文件

# -* - coding: UTF-8 -* -
#!/usr/bin/python


import os


path=r"D:\myapps"


#  checkFiles:遍历指定目录下的当层所有的文件(不包括文件夹)
def checkFiles(path):
    filesAndDirs = os.listdir (path)
    files = [ x  for x in filesAndDirs if os.path.isfile( path + os.sep + x ) ]  
    for file in files:
        print file


checkFiles(path)

3,替换某文件内字符串a为b

# -* - coding: UTF-8 -* -
#!/usr/bin/python

import os
import re

path=r"D:\myapps\python"
file=r"2.py"

#  findAndReplace:查找path路径下的直接文件filename并将stra替换为strb
def findAndReplace(path,filename,stra,strb):
    file=path+os.sep+filename
    f = open(file, 'r' )   
    filer = f.read()
    sub = re.sub(stra,strb,filer,0); #替换stra 为 strb
    f.close()
    f = open(file, 'w' )  
    f.write(sub)
    f.close()


findAndReplace(path,file,"math","thma")

4,替换指定路径下仅该层的所有文件的字符串替换操作

# -* - coding: UTF-8 -* -
#!/usr/bin/python

import os
import re


path=r"D:\myapps\python"
#  findAndReplace:查找path路径下的直接文件filename并将stra替换为strb
def findAndReplace(path,filename,stra,strb):
    file=path+os.sep+filename
    f = open(file, 'r' )   
    filer = f.read()
    sub = re.sub(stra,strb,filer,0); #替换stra 为 strb
    f.close()
    f = open(file, 'w' )  
    f.write(sub)
    f.close()
#  checkFiles:遍历指定目录下的当层所有的文件(不包括文件夹)
def checkFiles(path):
    filesAndDirs = os.listdir (path)
    files = [ x  for x in filesAndDirs if os.path.isfile( path + os.sep + x ) ]  
    for file in files:
        findAndReplace(path,file,"math","thma")


checkFiles(path)

5,指定路径下所有文件的字符串替换操作

# -* - coding: UTF-8 -* -
#!/usr/bin/python

import os
import re


path=r"D:\myapps"
#  findAndReplace:查找path路径下的直接文件filename并将stra替换为strb
def findAndReplace(path,filename,stra,strb):
    file=path+os.sep+filename
    f = open(file, 'r' )   
    filer = f.read()
    sub = re.sub(stra,strb,filer,0); #替换stra 为 strb
    f.close()
    f = open(file, 'w' )  
    f.write(sub)
    f.close()



#  checkFilesRec:遍历指定目录下的所有的文件(不包括文件夹)
def checkFilesRec(path):
    for root,dirs,files in os.walk(path):
        for file in files:
            findAndReplace(root,file,"math","thma")


checkFilesRec(path)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值