os模块
一、导入方式
import os
二、作用
与操作系统交互,可以操控文件
三、模块功能
3.1 经常使用
os.listdir():列出所有文件
print(os.listdir()) #列出所有文件
----------------------------------------------------------
['12.txt', '123', 'a.txt', 'access.log', 'db.txt', 'db.txt.swap', 'LeetCode.py']
os.rename() :重命名
os.remove() :删除
os.rename('m2.py','m1.py') #重命名m2.py
os.remove('m2.py') #删除m2.py
--------------------------------------------------------------
os.path.join():拼接文件路径(支持不同平台)
res = os.path.join(r'E:\python上海学习\02上课认真听讲\老师讲的内容\0816\04 os模块.py','m5.py') # 拼接文件路径
res = os.path.join(r'E:\python上海学习\02上课认真听讲\老师讲的内容\0816\04 os模块.py'm5','test.py')
# 拼接多个文件路径
-------------------------------------------------------------
os.path.abspath():返回文件规范化的绝对路径
os.path.abspath(__file__) #返回文件的绝对路径
os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #返回文件的上级目录的路径
3.1 一般使用
使用模块 | 功能 |
---|---|
os.getcwd() | 获取当前文件目录 |
os.mkdir('m2') | 创建一个m2的文件夹 |
os.rmdir('m2') | 删除m2文件夹 |
os.path.abspath(__file__) | 支持不同的平台(windows,ios,andirod等) |
os.path.exists('01 包.py') | 文件不存在False,存在True |
os.path.isfile('01 包.py') | 是否为文件 |
os.path.isdir('01 包.py') | 是否为文件夹 |
import os
g = os.walk(r'绝对路径。。。。') # 返回三个值,第一个值是路径;第二个值是路径下的文件夹,第三个值是路径下的文件
for i in g:
print(i)
四、计算函数代码
import os
import sys
def count_code(path): # path == '文件的绝对路径'
count = 0
flag = True
if os.path.isdir(path):
for dir, _, file_path_list in os.walk(path):
for file_path in file_path_list:
try:
file_path = os.path.join(dir, file_path)
path_list = file_path.split('.')
file_count = 0
if path_list[-1] == 'py':
with open(file_path, 'r', encoding='utf8') as fr:
for line in fr:
if (line.startswith('\'\'\'') or line.startswith('\"\"\"')) and flag:
flag = False
continue
elif ('=' in line and ('\'\'\'' in line or '\"\"\"' in line)) and flag:
flag = False
continue
elif (line.startswith('\'\'\'') or line.startswith('\"\"\"')) and not flag:
flag = True
continue
if line.startswith('#') and flag:
continue
elif line == '\n' and flag:
continue
elif flag:
count += 1
file_count += 1
print(f'{file_path}有{file_count}行')
except Exception:
print(f'该文件{file_path}有问题')
continue
elif os.path.isfile(path):
path_list = path.split('.')
if path_list[-1] == 'py':
file_count = 0
with open(path, 'r', encoding='utf8') as fr:
for line in fr:
if (line.startswith('\'\'\'') or line.startswith('\"\"\"')) and flag:
flag = False
continue
elif ('=' in line and ('\'\'\'' in line or '\"\"\"' in line)) and flag:
flag = False
continue
elif (line.startswith('\'\'\'') or line.startswith('\"\"\"')) and not flag:
flag = True
continue
if line.startswith('#') and flag:
continue
elif line == '\n' and flag:
continue
elif flag:
count += 1
file_count += 1
print(f'{path}有{file_count}行')
else:
print('不是py文件')
return count
if __name__ == '__main__':
# file_path = sys.argv[1]
# count = count_code(file_path)
count = count_code('文件(文件夹)绝对路径')
print(count)