|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +'练习操作文件和目录' |
| 5 | + |
| 6 | +__author__ = 'sergiojune' |
| 7 | +import os |
| 8 | +from datetime import datetime |
| 9 | + |
| 10 | +# 获取操作系统的类型 |
| 11 | +print(os.name) |
| 12 | +# window操作系统没有这个函数,在mac,linux下就会有 |
| 13 | +# print(os.uname()) |
| 14 | + |
| 15 | +# 环境变量 |
| 16 | +print(os.environ) |
| 17 | +# 获取某个环境变量的值 |
| 18 | +print(os.environ.get('path')) |
| 19 | + |
| 20 | +# 查看当前目录的绝对路径 |
| 21 | +print(os.path.abspath('.')) # . 表示当前路径 |
| 22 | + |
| 23 | +# 添加目录 |
| 24 | +name = os.path.join(os.path.abspath('.'), 'testtest') # 这步是解决不同系统目录名不一样的写法,是以目录形式合并两个参数 |
| 25 | +print(name) |
| 26 | +# 用上面的结果来添加目录 |
| 27 | +# os.mkdir(name) |
| 28 | +# 删除目录 |
| 29 | +# os.rmdir(name) |
| 30 | + |
| 31 | +name = os.path.join(os.path.abspath('.'), 'test29.py') |
| 32 | +print(name) |
| 33 | +# 分割路径,会分出文件名和目录名 |
| 34 | +l = os.path.split(name) |
| 35 | +print(l) |
| 36 | +# 也可以直接分出文件名的后缀 |
| 37 | +t = os.path.splitext(name) |
| 38 | +print(t) |
| 39 | +# 重命名 |
| 40 | +# os.rename('test.txt', 'test.md') |
| 41 | +# 删除文件 |
| 42 | +# os.remove('test.md') |
| 43 | +# 找出目标路径是目录的名字 |
| 44 | +d = [x for x in os.listdir(r'E:\anaconda\python_project') if not os.path.isdir(x)] |
| 45 | +print(d) |
| 46 | + |
| 47 | + |
| 48 | +# 作业 1 :利用os模块编写一个能实现dir -l输出的程序。 |
| 49 | +print('%s%30s' % ('type', 'name')) |
| 50 | +for x in os.listdir(r'E:\anaconda\python_project'): |
| 51 | + # 判断是否是文件 |
| 52 | + if os.path.isfile(x): |
| 53 | + file = os.path.splitext(x)[1] |
| 54 | + file = file.split('.')[1] |
| 55 | + print('%s%30s' % (file+' file', x)) |
| 56 | + else: |
| 57 | + print('%s%30s' % ('folder', x)) |
| 58 | + |
| 59 | + |
| 60 | +# 作业2:编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径 |
| 61 | +def find_dir(path, name, dirs=[]): |
| 62 | + for x in os.listdir(path): |
| 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 | +# 获取文件创建的时间 |
| 80 | +print(os.path.getmtime(d[0])) |
| 81 | +print(datetime.fromtimestamp(os.path.getmtime(d[0])).strftime('%Y-%m-%d %H:%M:%S') ) |
| 82 | +# 获取文件大小 |
| 83 | +print(os.path.getsize(d[0])//1024, 'KB') |
| 84 | + |
0 commit comments