1. 程式人生 > >小甲魚《零基礎學習Python》課後筆記(三十):檔案系統——介紹一個高大上的東西

小甲魚《零基礎學習Python》課後筆記(三十):檔案系統——介紹一個高大上的東西

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

程式碼如下:

import os 
filename_list = os.listdir(os.curdir)
filetype_dict = dict()

for each_file in filename_list:
	if os.path.isdir(each_file):
		filetype_dict.setdefault('資料夾', 0)	# 如果鍵不存在於字典中,將會新增鍵並將值設為預設值
		filetype_dict['資料夾'] += 1
	else:
		file_type = os.path.
splitext(each_file)[1] #返回的是元組,第一個是檔名,第二個是副檔名 filetype_dict.setdefault(file_type, 0) filetype_dict[file_type] += 1 for each_type in filetype_dict.keys(): print('該資料夾下共有型別為【%s】的檔案%d個' % (each_type, filetype_dict[each_type]))

測試結果:

================== RESTART: I:\Python\小甲魚\test003\test0.py ========
========== 該資料夾下共有型別為【.mp3】的檔案2個 該資料夾下共有型別為【.txt】的檔案2個 該資料夾下共有型別為【.py】的檔案1
1.編寫一個程式,計算當前資料夾下所有檔案的大小,程式實現如圖:


程式碼如下:

import os
filename_list = os.listdir(os.curdir)
file_dict = dict()

for each_file in filename_list:
	file_size = os.path.getsize(each_file)
	file_dict.setdefault(each_file, file_size)
for each_file in file_dict.keys(): print('%s【%d】Bytes' % (each_file, file_dict[each_file]))

測試結果:

================== RESTART: I:\Python\小甲魚\test003\test0.py ==================  
Readme.mp3【5733532】Bytes  
something.txt【106】Bytes  
test0.py【292】Bytes  
聽寫1.mp3【992235】Bytes  
我.txt【122】Bytes  
2.編寫一個程式,使用者輸入檔名以及開始搜尋的路徑,搜尋該檔案是否存在。如遇到資料夾,則進入資料夾繼續搜尋,程式實現如圖:


程式碼如下:

import os

def search_file(search_dir, search_target):
	"查詢目錄下的檔案並輸出路徑"
	os.chdir(search_dir)
	for each_file in os.listdir(os.curdir):
		if each_file == search_target:
			print(os.getcwd() + os.sep + each_file)
		if os.path.isdir(each_file):
			search_file(each_file, search_target)
			os.chdir(os.pardir)

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

測試結果:

1.	================== RESTART: I:\Python\小甲魚\test003\test0.py ==================  
2.	請輸入待查詢的初始目錄:K:\\影象  
3.	請輸入需要查詢的目標檔案:9.png  
4.	K:\影象\9.png  
5.	K:\影象\新建資料夾\9.png  
6.	K:\影象\新建資料夾\新建資料夾\9.png 

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


程式碼如下:

import os

def search_vedio(search_dir):
	"查詢目錄下的所有視訊格式檔案,並建立一個檔案儲存檔案的路徑"
	os.chdir(search_dir)
	for each_file in os.listdir(os.curdir):
		if os.path.splitext(each_file)[1] in file_type_list:
			file_name = os.getcwd() + os.sep + each_file + os.linesep
			file_list.append(file_name)
		if os.path.isdir(each_file):
			search_vedio(each_file)
			os.chdir(os.pardir)
			
file_type_list = ['.mp4', '.rmvb', '.avi', '.wmv']
file = open(os.getcwd() +os.sep + 'vedioList.txt', 'w')
file_list = []

search_dir = input('請輸入待查詢的初始目錄:')
search_vedio(search_dir)
file.writelines(file_list)
file.close()
4.編寫一個程式,使用者輸入關鍵字,查詢當前資料夾內(如果當前資料夾內包含資料夾,則進入資料夾繼續搜尋)所有含有該關鍵字的文字檔案(.txt字尾),要求顯示該檔案所在的位置以及關鍵字在檔案中的具體位置(第幾行第幾個字元),程式實現如圖:


程式碼如下:

import os


def print_pos(target_words_dict):
	keys = target_words_dict.keys()
	keys = sorted(keys)
	for each_key in keys:
		print('關鍵字出現在第%s行,第%s個位置。' % (each_key, str(target_words_dict[each_key])))


def pos_in_line(line, target_words):
	pos = []
	count = line.find(target_words)
	while count != -1:
		pos.append(count + 1)	#字元索引從0開始
		count = line.find(target_words, count + 1)	#從下一個位置開始查詢


	return pos


def search_in_file(file_name, target_words):
	file = open(file_name)
	line_count = 0
	target_words_dict = dict()
	for each_line in file:
		line_count += 1
		if target_words in each_line:
			pos = pos_in_line(each_line, target_words)
			target_words_dict[line_count] = pos

	file.close()
	return target_words_dict


def search_words(target_words, option):
	files = os.walk(os.getcwd())
	target_files = []

	for each in files:
		for each_file in each[2]:
			if os.path.splitext(each_file)[1] == '.txt':
				each_file = os.path.join(each[0], each_file)
				target_files.append(each_file)

	for each in target_files:
		target_words_dict = search_in_file(each, target_words)
		if target_words_dict:
			print('==============================================')
			print('在檔案【%s】中找到關鍵字【%s】' % (each, target_words))
			if option.upper() == 'YES':
				print_pos(target_words_dict)
	
target_words = input('請將該指令碼放於待查詢的資料夾內,請輸入關鍵字:')
option = input('請問是否需要列印關鍵字【%s】在檔案中的具體位置(YES/NO):')
search_words(target_words, option)