morganlions的博客

python 学习点点滴滴

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)
阅读更多
版权声明:未经本人同意,禁止转载! https://blog.csdn.net/TianPingXian/article/details/80334902
文章标签: 文件扫描 python
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭