day18

        跨文件夹转移到文件

#将part5 下的mm.py 移动到part6abc文件夹

import os

import sys

BASE_BIR = os.path.dirname(os.path.dirname(__file__))

sys.path.append(BASE_DIR)

 

def move_file(file,folder):

    if not (os.path.exists(file) and os.path.isfile(file)):

     print('文件不存在或非法')

   return False

    if not as path.exists(folder):

       os.makedirs(folder)

   file_name = os.path.split(file)[1]

  new_file = os.path.join(folder,file_name)

 

with open(file,'rb') as rf,open(new_file,'wb') as wf:

    for line in rf:

       wf.write(line)

os.remove(file)                     #核心部分:复制代码,删除原代码

 

file = os.path.join(BASE_DIR,'part5','mm.py')

folder = os.path.join(BASE_DIR,'part6','abc')

move_file(file,folder)

 

 遍历打印目标路径中所以txt文件

 

def print_txt(folder):

   if not os.path.exists(folder) or os.path.isfile(folder):

       return

   for path in os.listdir(folder):

        file_path = os.listdir(folder)

        if os.path.isfile(file_path) and file_path.endswith('.txt'):

           print(path) #.txt文件

        elif os.path.isdir(file_path):

           print_txt(file_path)    #递归 文件夹中.txt文件     

        

 

posted @ 2019-05-07 23:26  呼吸决定丶  阅读(58)  评论(0)    收藏  举报