python 扫描目录下制定类型文件 并打印出来使用os.walk

import os, random

import pyperclip


def scan_file(directory, prefix=None, postfix=None):
    '''
    :param directory: 
    :param prefix: 
    :param postfix: 
    :return: 
    '''
    files_lists = []
    for root, sub_dirs, files in os.walk(directory):
        for special_file in files:
            if postfix:
                if special_file.endswith(postfix):
                    files_lists.append(os.path.join(root, special_file))
            elif prefix:
                if special_file.startswith(prefix):
                    files_lists.append(os.path.join(root, special_file))
    return files_lists


def readTxt(path, type='open', text=None):
    fileList = scan_file(path, postfix='txt')
    textList = []
    for i in range(len(fileList)):
        if type == 'open':
            readFile = open(fileList[i], 'r')
            textList.append(readFile.read())
        elif type == 'write' and os.path.exists(fileList[i]):
            readFile = open(fileList[i], 'a')
            readFile.write(text)
            return '写入成功'
    return ''.join(textList)


text = 'My name is Morgan {0}\n\n'.format(random.randint(1, 20))
path = '/www/wwwpython/test/'
result = readTxt(path, type='open', text=text)
print(result)
pyperclip.copy(result)

猜你喜欢

转载自blog.csdn.net/tianpingxian/article/details/80334902