-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_operator_tools.py
76 lines (60 loc) · 1.88 KB
/
file_operator_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
文件操作相关函数
"""
import os
from os.path import join, isdir, abspath, pardir, basename, getmtime
import time
def listdir(dir):
"""遍历dir文件夹,返回目录列表和文件列表"""
dirs = []
files = []
for item in os.listdir(dir):
full_name = join(dir, item)
if isdir(full_name):
dirs.append(item)
else:
files.append(item)
return dirs, files
def get_m_time(start, paths):
"""
获取文件或目录的创建时间
:param start: 起始目录
:param paths: 文件或目录的名字的列表
:return: 返回包含元组(path, m_time)类型的列表
"""
lst = []
for path in paths:
full_path = join(start, path)
m_time = getmtime(full_path)
lst.append((path, time.asctime( time.localtime(m_time) ) ) )
return lst
def get_levels(start, path):
"""
获取path每一层的路径, 以start为起始目录 (应确保path在start下)
:param start: 根目录绝对路径
:param path: 路径绝对路径
:return: 包含每层目录的绝对路径的列表
"""
levels = []
full_path = path
base_name = basename(full_path)
levels.append((full_path, base_name))
while full_path != start:
full_path = abspath(join(full_path, pardir)) # 移动到父目录
base_name = basename(full_path)
levels.append((full_path, base_name))
return levels[ : : -1] # 返回反转后的列表
def get_abs_path(start, path):
"""
获取path的绝对路径,
:param start: 根目录
:param path: 相对路径
:return: 如果path不在start下返回None, 反之返回其绝对路径
"""
if start and path:
# start 和 path 都不能为空
start = abspath(start)
abs_path = abspath(path)
if abs_path.startswith(start):
return abs_path
return None