需求:
统计目前学习Python一共写了多少代码(注释不算)
1、指定文件代码行数统计算法
2、实现递归统计某个文件夹中所有.py文件的代码行数
# 指定文件代码行数统计算法
def irisCodeCounter(filePath):
# 记录代码的总行数
lines=0
# 打开文件
file = open(filePath,'r',encoding='utf-8')
# 读取内容
content=file.readline()
# 设置读取有效Python编码开关,主要是用来排除掉多行注释,默认不是多行注释中的内容
add = True
while content !='':
str = '"""'
if str in content:
add = not add
if add:
if '#' not in content:
lines+=1
content = file.readline()
file.close()
return lines
import os
def totalCodeCounter(dir):
files=os.listdir(dir)
# 用来统计总代码数量
total = 0
# 用来记录单个文件的代码数量
singleFileCodeNum = 0
for file_name in files:
# print(type(file_name))
# 文件或文件夹的全路径
file_path = dir+'/'+file_name
# 如果是文件,那么就记录代码量,如果是文件夹就递归
if os.path.isfile(file_path):
if file_name.endswith('.py'):
singleFileCodeNum=irisCodeCounter(file_path)
print('当前文件:%s\t代码行数->%s'%(file_path,singleFileCodeNum))
total += singleFileCodeNum
elif os.path.isdir(file_path):
total += totalCodeCounter(file_path)
return total
# 测试指定文件代码行数统计算法
curr_dir=os.getcwd()
print(curr_dir)
file_name='demo6.py'
lines=irisCodeCounter(curr_dir+"//"+file_name)
print(lines)
# 所有.py文件的代码行数
# 当前文件夹代码总行数
# print(totalCodeCounter(curr_dir))
# 至今所有代码总行数
print(totalCodeCounter('E:/workspace/ideaProjects/w1/pythonbase'))
控制台截图

需求:
批量修改文件名
作用:
在编写Python代码的时候,命名001.py文件是不会报错的,可以在001.py文件中添加Python代码;但是当demo1.py中要引用001.py的时候,是不能导入成功的;这时我们需要批量修改数字开头的.py文件,让其文件命名符合规范才能导入其它的.py文件中使用;
import os
# oldName='001.py'
# newName='javaxl_'+oldName
# os.rename(oldName,newName)
# 找到所有文件,修改文件名
def rename_files(dirPath,joinStr):
allFiles = os.listdir(dirPath)
for file in allFiles:
filePath=dirPath+"/"+file
if os.path.isfile(filePath):
if file[0].isdigit() and file.endswith('.py'):
newName=dirPath+'/'+joinStr+file
print(newName)
os.rename(filePath,newName)
elif os.path.isdir(filePath):
rename_files(filePath,joinStr)
rename_files(os.getcwd(),'javaxl_')
控制台截图

over......
备案号:湘ICP备19000029号
Copyright © 2018-2019 javaxl晓码阁 版权所有