1. 程式人生 > >pyhon檔案操作典型程式碼實現(非常經典!)

pyhon檔案操作典型程式碼實現(非常經典!)

1. 編寫一個程式,統計當前目錄下每個檔案型別的檔案數,程式實現如圖:

實現程式碼:

import os

all_files = os.listdir(os.chdir("D:\\"))
type_dict = dict()

for each_file in all_files:
if os.path.isdir(each_file):
type_dict.setdefault('資料夾', 0)
type_dict['資料夾'] += 1
else:
ext = os.path.splitext(each_file)[1]
type_dict.setdefault(ext, 0)
type_dict[ext] += 1

for each_type in type_dict.keys():
print('該資料夾下共有型別為【%s】的檔案 %d 個' % (each_type, type_dict[each_type]))

2、編寫一個程式,計算當前資料夾下所有檔案的大小:

import os

all_files = os.listdir(os.chdir("D:\\")) # 使用os.curdir表示當前目錄更標準
file_dict = dict()

for each_file in all_files:
if os.path.isfile(each_file):
file_size = os.path.getsize(each_file)
file_dict[each_file] = file_size

for each in file_dict.items():
print('%s【%dBytes】' % (each[0], each[1]))

3、編寫一個程式,使用者輸入檔名以及開始搜尋的路徑,搜尋該檔案是否存在。如遇到資料夾,則進入資料夾繼續搜尋

import os

def search_file(start_dir, target) :
os.chdir(start_dir)

for each_file in os.listdir(os.chdir("C:\\")) :
if each_file == target :
print(os.getcwd() + os.sep + each_file) # 使用os.sep是程式更標準
if os.path.isdir(each_file) :
search_file(each_file, target) # 遞迴呼叫
os.chdir(os.pardir) # 遞迴呼叫後切記返回上一層目錄

start_dir = input('請輸入待查詢的初始目錄:')
target = input('請輸入需要查詢的目標檔案:')
search_file(start_dir, target)

4、 編寫一個程式,使用者輸入開始搜尋的路徑,查詢該路徑下(包含子資料夾內)所有的視訊格式檔案(要求查詢mp4 rmvb, avi的格式即可),並把建立一個檔案(vedioList.txt)存放所有找到的檔案的路徑,程式實現如圖:

import os

def search_file(start_dir, target) :
os.chdir(start_dir)

for each_file in os.listdir(os.curdir) :
ext = os.path.splitext(each_file)[1]
if ext in target :
vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # 使用os.sep是程式更標準
if os.path.isdir(each_file) :
search_file(each_file, target) # 遞迴呼叫
os.chdir(os.pardir) # 遞迴呼叫後切記返回上一層目錄

start_dir = input('請輸入待查詢的初始目錄:')
program_dir = os.getcwd()

target = ['.mp4', '.avi', '.rmvb']
vedio_list = []

search_file(start_dir, target)

f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list)
f.close()

5、編寫一個程式,使用者輸入關鍵字,查詢當前資料夾內(如果當前資料夾內包含資料夾,則進入資料夾繼續搜尋)所有含有該關鍵字的文字檔案(.txt字尾),要求顯示該檔案所在的位置以及關鍵字在檔案中的具體位置(第幾行第幾個字元)

import os

def print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys) # 由於字典是無序的,我們這裡對行數進行排序
for each_key in keys:
print('關鍵字出現在第 %s 行,第 %s 個位置。' % (each_key, str(key_dict[each_key])))


def pos_in_line(line, key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1) # 使用者的角度是從1開始數
begin = line.find(key, begin+1) # 從下一個位置繼續查詢

return pos


def search_in_file(file_name, key):
f = open(file_name)
count = 0 # 記錄行數
key_dict = dict() # 字典,使用者存放key所在具體行數對應具體位置

for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line, key) # key在每行對應的位置
key_dict[count] = pos

f.close()
return key_dict


def search_files(key, detail):
all_files = os.walk(os.curdir)
txt_files = []

for i in all_files:
for each_file in i[2]:
if os.path.splitext(each_file)[1] == '.txt': # 根據字尾判斷是否文字檔案
each_file = os.path.join(i[0], each_file)
txt_files.append(each_file)

for each_txt_file in txt_files:
key_dict = search_in_file(each_txt_file, key)
if key_dict:
print('================================================================')
print('在檔案【%s】中找到關鍵字【%s】' % (each_txt_file, key))
if detail in ['YES', 'Yes', 'yes']:
print_pos(key_dict)


key = input('請將該指令碼放於待查詢的資料夾內,請輸入關鍵字:')
detail = input('請問是否需要列印關鍵字【%s】在檔案中的具體位置(YES/NO):' % key)
search_files(key, detail)