python-常用小程序-文件夹
1,递归遍历文件夹下所有文件# -* - coding: UTF-8 -* -#!/usr/bin/pythonimport ospath=r"D:\myapps"# checkFilesRec:遍历指定目录下的所有的文件(不包括文件夹)def checkFilesRec(path): for root,dirs,files in os.walk(path)
·
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)
更多推荐
已为社区贡献2条内容
所有评论(0)