Python小程序 - 文件解析

1. 目录下文件解析:特定文件、文件列表、文件数

  • Windows文件目录分格使用“ / ” 或 “ \\ ”
  • 文件目录路径包含空格的,绝对路径使用“双引号”,保证文件路径的可识别性
  • 保存和读取结果时,使用 encoding='UTF-8'
  • 可以添加对文件目录的过滤
# FileFindInFolder.py

import os

fd = "H:/My/Study/Python"   # source folder
ef = '.pdf'                 # specified file suffix for finding
rf = "c:/record.txt"        # final result output
lrf = []                    # list for result output
cn = 0                      # count for file find

for root, dirs, files in os.walk(fd):  # travel and check all folders and files
    for i in files:
        if i.endswith(ef):             # file specified ending
            cn = cn + 1
            fpath = root + i           # file full path
            lrf.append(fpath)

# result output and save
with open(rf, 'w', encoding='UTF-8') as fp:
    fp.write("Total: " + str(cn) + '\n')
    for i in lrf:
        fp.write(i + '\n')

# read file and show content
with open(rf, 'r', encoding='UTF-8') as fp:
    fl = fp.readlines()
    for i in fl:
        print(i)

>>>
Total: 40

H:/My/Study/Pythondjango 3.1.pdf

H:/My/Study/Pythondjango.pdf

H:/My/Study/PythonPyQt5中文教程.pdf          

2. 文件内容解析

  • 文件读取来自linux系统
  • 查找当前文件夹所有文件并显示文件大小,结果输出到指定文件
  • 文本样例
    8       ./.local/share/evolution/mail
    60      ./.local/share/evolution
    596     ./.local/share/zeitgeist/fts.index
    1900    ./.local/share/zeitgeist
    4       ./.local/share/sounds
    20      ./.local/share/icons
    8       ./.local/share/telepathy/mission-control
  • 实际文件读取显示
    b'4\t./Public\n'
    b'4\t./Pictures\n'
    b'76\t./.local/share/gvfs-metadata\n'
    b'4\t./.local/share/unity-settings-daemon\n'
    b'20\t./.local/share/unity-webapps\n'
    b'8\t./.local/share/applications\n'
    b'4\t./.local/share/evolution/tasks/trash\n'
    b'8\t./.local/share/evolution/tasks/system\n'
# FileCal.py

fn = './example.txt'  # source file
dicf = {}             # dictory for folder, file count and total file size
tsize = 0             # total size

with open(fn, 'rb') as fp:
    rf = fp.readlines()
    for i in rf:
        li = str(i).replace('b','').replace('t',' ').replace('n','').replace('\\','').replace('\'','')   # special char should be replaced; example: b'4\t./Public\n'
        ls = li.split(' ',1)     # only split file size and folder using first space
 
        fsize = int(ls[0])       # file size
        tsize = tsize + fsize
        fdf = ls[1]              # dir and file
        
        tl = fdf.split('/')      # seperate dir and file
        pdir = ''
        for i in range(len(tl)-1):
            pdir = pdir + tl[i] + '/'


        if not dicf.get(pdir):   # dictory: key - dir, value - file size
            dicf[pdir] = fsize
        else:
            dicf[pdir] = dicf[pdir] + fsize


# print dir and inclued file size, total file size
for i in dicf:
    print("%-50s" %(i), ' : ', "%10s" %(dicf[i]), ' K')     # format output

print("Toal Size: ", tsize, ' K')   

>>>
/                                                  :      571040  K
./.local/share/                                     :        4268  K
./.local/share/evolu io/ asks/                      :          24  K
./.local/share/evolu io/                            :         112  K
./.local/share/evolu io/memos/                      :           8  K
./.local/share/evolu io/addressook/                 :           8  K
./.local/share/evolu io/caledar/                    :          24  K
./.local/share/evolu io/mail/                       :           8  K
./.local/share/zei geis /                           :        3088  K
./.local/share/ elepa hy/                           :          16  K
./.local/share/au ilus/                             :           8  K
./.local/                                           :        4304  K
./Docume s/                                         :           4  K
./.gcof/apps/                                       :          16  K
...... omit ...
./Desk op/                                          :          24  K
./.kde/share/apps/kcof_upda e/log/                  :           8  K
./Dowloads/firefox (2)/g k2/                        :          16  K
./Dowloads/firefox (2)/gmp-clearkey/0.1/            :         104  K
./Dowloads/firefox (2)/fo s/                        :        1200  K
./Dowloads/firefox (2)/rowser/chrome/icos/defaul /  :          12  K
./Dowloads/firefox (2)/rowser/ex esios/             :           4  K
./Dowloads/firefox (2)/rowser/icos/                 :          20  K
./Dowloads/firefox (2)/rowser/fea ures/             :        4160  K
./Dowloads/firefox (2)/dic ioaries/                 :         568  K
./Dowloads/firefox (2)/icos/                        :           4  K
./Dowloads/firefox (2)/defaul s/pref/               :           4  K
Toal Size:  1359440  K

你可能感兴趣的:(My,Coding,python)