PT--OS 模块与序列化模块

 

 

# 1、写一个函数,接受一个参数,如果是文件,就执行这个文件,如果是文件夹,就执行这个文件夹下所有的py文件
import os
def func(path):
        if os.path.isfile(path) and path.endswith('.py'): #判断是否为文件且 .py文件
            os.system('python %s'%path)  # os.system()可以执行操作系统命令
        elif os.path.isdir(path):
            for name in os.listdir(path):
                abs_path = os.path.join(path,name)
                if abs_path.endswith('.py'):
                    os.system('python %s'%abs_path)
func(r'E:\workplace\ceshi\yh\2.py')

# 2、写一个copy函数,接受两个参数,第一个参数是源文件的位置,第二个参数是目标位置,将源文件copy到目标位置。
import os
def copy(path1,path2):
    filename = os.path.basename(path1)
    if os.path.isfile(path1) and os.path.isdir(path2):  # 判断路径1是文件,路径2是文件夹
        path2 = os.path.join(path2,filename)
        if os.path.exists(path2):
            print('已有同名文件')
        with open(path1,'rb') as f1,\
            open(path2,'wb') as f2:
            content = f1.read()
            f2.write(content)
copy(r'D:\sylar\s15\day19\1.内容回顾.py',r'D:\sylar\s15\day18')

# 3、获取某个文件所在目录的上一级目录。
# 例如'D:\sylar\s15\day19\6.序列化模块.py'目录的结果 :D:\sylar\s15
# 方法1
import os
path = os.path.dirname(r'D:\sylar\s15\day19\6.序列化模块.py')
base_name = os.path.dirname(path)
print(base_name)
# 方法2 函数
def func(path):
    for i in range(2):
        top_path = os.path.dirname(path)
        path = top_path
    return path
top = func(r'E:\workplace\ceshi\yh\2.py')
print(top)

# 4、使用os模块创建如下目录结构
# glance/
#
# ├── __init__.py
#
# ├── api
#
# │   ├── __init__.py
#
# │   ├── policy.py
#
# │   └── versions.py
#
# ├── cmd
#
# │   ├── __init__.py
#
# │   └── manage.py
#
# └── db
#
#     ├── __init__.py
#
#     └── models.py

# 创建文件夹 创建文件(open文件write)
import os
os.makedirs('glance/api')
os.makedirs('glance/cmd')
os.makedirs('glance/db')
open('glance/api/__init__.py','w').close()
open('glance/api/policy.py','w').close()
open('glance/api/version.py','w').close()
open('glance/cmd/__init__.py','w').close()
open('glance/cmd/manage.py','w').close()
open('glance/db/__init__.py','w').close()
open('glance/db/models.py','w').close()


# 5. os模块:
    # 用户登录 ,登录之后 给这个用户创建一个属于他的文件夹 已用户名命名
    # 如果用户注销,删除这个文件夹

import os
u_name = input('输入用户名:')
p_word = input('输入密码:')
if u_name == 'chen' and p_word == '1234':
    print('登陆成功')
    path = os.path.join(r'E:\A学习\python--study\untitled\0820--day18',u_name)
    # 判断文件名是否存在  不存在则创建
    if os.path.exists(path):
        pass
    else:
        os.mkdir(u_name)
    content = input('退出登录(Q或q), 注销用户(N或n):')
    if content.upper() == 'Q':
        exit()
    elif content.upper() == 'N':
        os.rmdir(u_name)
else:
    print('登录失败')

 

posted @ 2018-08-22 15:29  葡萄想柠檬  Views(257)  Comments(0)    收藏  举报
目录代码