path
# 创建文件夹
folder = os.path.join('aaa', 'bbb')
os.makedirs(folder, exist_ok=True)
1
2
2
# 删除
os.remove(file) #只能删除文件,不能删除文件夹
shutil.rmtree(folder_name) #删除文件夹
1
2
3
2
3
# 复制
shutil.copyfile(arg.out_file, arg.in_file)
1
# split分割路径
fullpath = " D:/download/repository.7z ".strip()
# case 1 分隔路径和文件名:
folder_path, filename = os.path.split(fullpath)
print (folder_path) # D:/download
print (filename) # repository.7z
# case 2, 分隔扩展名:
folder_path, ext = os.path.splitext(fullpath)
print (folder_path) # D:/download/repository
print (ext) # .7z 注意这里有个点
# case 3, 分隔盘符:
drv, left = os.path.splitdrive(fullpath);
print (drv) # D:
print (left) # /download/repository.7z
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
查看文件或文件夹是否存在
print os.path.exists("/untitled/chapter3.py")
print os.path.exists("chapter3.py")
1
2
3
2
3
# 遍历文件夹
https://www.cnblogs.com/wt7018/p/11610286.html
import os
# 遍历文件夹
def walkFile(file):
for root, dirs, files in os.walk(file):
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list, 包括子目录中的文件
# 遍历文件
for f in files:
filename = os.path.join(root, f)
print(filename)
# 遍历所有的文件夹
for d in dirs:
folder = os.path.join(root, d)
print(folder)
def main():
walkFile("f:/ostest/")
if __name__ == '__main__':
main()
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
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
遍历某个文件夹下的所有文件和目录,不包括子目录下的文件
for file_name in os.listdir(tar_dir):
print(file_name)
1
2
3
2
3
寻找某个文件
def search_file(path,name):
for root, dirs, files in os.walk(path): # path 为根目录
if name in dirs or name in files:
return os.path.join(root, name)
1
2
3
4
5
6
7
2
3
4
5
6
7
# 判断是文件还是文件夹
if os.path.isdir(path):
print "it's a directory"
elif os.path.isfile(path):
print "it's a normal file"
else:
print "it's a special file(socket,FIFO,device file)"
1
2
3
4
5
6
2
3
4
5
6
编辑 (opens new window)
上次更新: 2022/05/18, 01:07:09