Skip to content

Commit 5fe2f60

Browse files
authored
练习操作文件和目录
1 parent b0f2d87 commit 5fe2f60

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

test30.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
'练习操作文件和目录'
5+
6+
__author__ = 'sergiojune'
7+
import os
8+
9+
# 获取操作系统的类型
10+
print(os.name)
11+
# window操作系统没有这个函数,在mac,linux下就会有
12+
# print(os.uname())
13+
14+
# 环境变量
15+
print(os.environ)
16+
# 获取某个环境变量的值
17+
print(os.environ.get('path'))
18+
19+
# 查看当前目录的绝对路径
20+
print(os.path.abspath('.')) # . 表示当前路径
21+
22+
# 添加目录
23+
name = os.path.join(os.path.abspath('.'), 'testtest') # 这步是解决不同系统目录名不一样的写法,是以目录形式合并两个参数
24+
print(name)
25+
# 用上面的结果来添加目录
26+
# os.mkdir(name)
27+
# 删除目录
28+
# os.rmdir(name)
29+
30+
name = os.path.join(os.path.abspath('.'), 'test29.py')
31+
print(name)
32+
# 分割路径,会分出文件名和目录名
33+
l = os.path.split(name)
34+
print(l)
35+
# 也可以直接分出文件名的后缀
36+
t = os.path.splitext(name)
37+
print(t)
38+
# 重命名
39+
# os.rename('test.txt', 'test.md')
40+
# 删除文件
41+
# os.remove('test.md')
42+
# 找出目标路径是目录的名字
43+
d = [x for x in os.listdir(r'E:\anaconda\python_project') if not os.path.isdir(x)]
44+
print(d)
45+
46+
47+
# 作业 1 :利用os模块编写一个能实现dir -l输出的程序。
48+
print('%s%30s' % ('type', 'name'))
49+
for x in os.listdir(r'E:\anaconda\python_project'):
50+
# 判断是否是文件
51+
if os.path.isfile(x):
52+
file = os.path.splitext(x)[1]
53+
file = file.split('.')[1]
54+
print('%s%30s' % (file+' file', x))
55+
else:
56+
print('%s%30s' % ('folder', x))
57+
58+
59+
# 作业2:编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径
60+
def find_dir(path, name, dirs=[]):
61+
for x in os.listdir(path):
62+
p = path + x
63+
if os.path.isfile(path+'\\'+x):
64+
# 文件中有指定字符串
65+
if name in x:
66+
dirs.append(path+'\\'+x)
67+
# 文件夹
68+
else:
69+
if name in x:
70+
dirs.append(path+'\\'+x)
71+
# 递归
72+
find_dir(os.path.join(path, x), name)
73+
return dirs
74+
75+
76+
d = find_dir(r'E:\anaconda\python_project', 'py')
77+
print(d)
78+
79+

0 commit comments

Comments
 (0)