1. 程式人生 > 實用技巧 >檔案操作和序列化

檔案操作和序列化

#1.寫一個函式如果是py檔案就執行,如果是資料夾就執行資料夾下的py檔案

#注意 檔案路徑不能有空格和中文,同一時間執行多臺電腦檔案
def func(path):
    if os.path.isfile(path) and path.endswith('.py'):
        os.system('python %s'%path)

    elif os.path.isdir(path):
         file_list = os.listdir(path)
         for file in file_list:
             file_new = os.path.join(path,file)
             
if os.path.isfile(file_new) and file_new.endswith('.py'): os.system('python %s'%file_new) func(r'D:\workspace\com\baizhi\practice\day18')

2.寫一個copy函式

def copy(path1,path2):
    file = os.path.basename(path1)
    if os.path.isfile(file) and os.path.isdir(path2):
        path2 = os.path.join(path1)
        
if os.path.exists(path2):print('已有同名檔案') with open(path1,mode='rb')as f1,\ open(path2,mode='wb')as f2: content = f1.read() f2.write(content)

3.建立多級目錄

os.makedirs('glance/cmd') #os模組建立資料夾
open(r'glance\cmd\__init__.py','w').close()#建立檔案

4.序列化儲存的登入註冊

import pickle
def regist():
    user = input('輸入名字:')
    pwd = input('輸入密碼:')
    dic ={'user':user,'pwd':pwd}
    with open('json_file2',mode='ab') as f:
        pickle.dump(dic,f)
def login():
    user = input('輸入名字:')
    pwd = input('輸入密碼:')
    with open('json_file2',mode='rb')as f:
        dic = pickle.load(f)
        while dic:
            try:
                if user ==dic['user'] and pwd == dic['pwd']:
                    print('登入成功')
                    break
            except EOFError:
                print('登入失敗')
regist()
login()