Python基礎之文件目錄操做

概述

I/O操做不只包括屏幕輸入輸出,還包括文件的讀取與寫入,Python提供了不少必要的方法和功能,進行文件及文件夾的相關操做。本文主要經過兩個簡單的小例子,簡述Python在文件夾及文件的應用,僅供學習分享使用,若有不足之處,還請指正。數組

涉及知識點

  1. os模塊:os 模塊提供了很是豐富的方法用來處理文件和目錄。
  2. open方法:open方法用於打開一個文件,用於讀取和寫入。

實例1:獲取指定目錄下全部的文件大小,並找出最大文件及最小文件

分解步驟:

  1. 遍歷文件夾下全部的子文件及子文件夾(須要遞歸),並計算每個文件的大小
  2. 計算全部文件的大小總和
  3. 找出最大文件及最小文件

核心代碼

定義一個方法get_file_size,獲取單個文件的大小,單位有KB和MB兩種。關鍵點以下所示:app

  1. os.path.getsize 用於獲取指定文件的大小,單位是Byte。
  2. round爲四捨五入函數,保留指定位數的小數。
 1 def get_file_size(file_path, KB=False, MB=False):
 2     """獲取文件大小"""
 3     size = os.path.getsize(file_path)
 4     if KB:
 5         size = round(size / 1024, 2)
 6     elif MB:
 7         size = round(size / 1024 * 1024, 2)
 8     else:
 9         size = size
10     return size

定義一個方法list_files,遍歷指定文件目錄,並存入字典當中。關鍵點以下所示:函數

  1. os.path.isfile 用於判斷給定的路徑是文件仍是文件夾。
  2. os.listdir 用於獲取指定目錄下全部的文件及文件夾,返回一個列表,可是隻是當前文件夾的名稱,並非全路徑。
  3. os.path.join 用於拼接兩個路徑
 1 def list_files(root_dir):
 2     """遍歷文件"""
 3     if os.path.isfile(root_dir):  # 若是是文件
 4         size = get_file_size(root_dir, KB=True)
 5         file_dict[root_dir] = size
 6     else:
 7         # 若是是文件夾,則遍歷
 8         for f in os.listdir(root_dir):
 9             # 拼接路徑
10             file_path = os.path.join(root_dir, f)
11             if os.path.isfile(file_path):
12                 # 若是是一個文件
13                 size = get_file_size(file_path, KB=True)
14                 file_dict[file_path] = size
15             else:
16                 list_files(file_path)

計算總大小和最大文件及最小文件,以下所示:學習

經過比較字典value的大小,返回對應的key的名稱。關鍵點以下所示:編碼

  1. max_file = max(file_dict, key=lambda x: file_dict[x])
  2. min_file = min(file_dict, key=lambda x: file_dict[x])
 1 if __name__ == '__main__':
 2     list_files(root_dir)
 3     # print( len(file_dict))
 4     # 計算文件目錄大小
 5     total_size = 0
 6     # 遍歷字典的key
 7     for file in file_dict:
 8         total_size += file_dict[file]
 9 
10     print('total size is : %.2f' % total_size)
11     # 找最大最小文件
12     max_file = max(file_dict, key=lambda x: file_dict[x])
13     min_file = min(file_dict, key=lambda x: file_dict[x])
14     print('max file is : ', max_file, '\n file size is :', file_dict[max_file])
15     print('min file is : ', min_file, '\n file size is :', file_dict[min_file])

實例2:將兩個文本文件中的內容進行合併,並保存到文件中

兩個文件內容,以下圖所示:spa

分解步驟:

  1. 讀取兩個文件中的內容並進行解析出key和value,存入字典當中(兩個字典,分別存儲兩個文件的內容)。
  2. 遍歷第1個字典,並查找第2個字典當中相同key的值,如不存在,則只顯示第1個內容,如存在,則進行合併。
  3. 遍歷第2個字典,並查找不在第1個字典當中的key的值,進行累加。
  4. 將拼接後的列表存入文件當中。

核心代碼

定義一個函數read_book,用於讀取兩個文件的內容。關鍵點以下所示:code

  1. open函數用於打開一個文件,文件編碼爲UTF-8。
  2. readlines用於讀取全部的行,並返回一個列表。
  3. split用於分割字符串爲數組。
 1 def read_book():
 2     """讀取內容"""
 3     # 讀取一個文件
 4     file1 = open('book1.txt', 'r', encoding='UTF-8')
 5     lines1 = file1.readlines()
 6     file1.close()
 7     for line in lines1:
 8         line = line.strip()  # 去空白
 9         content = line.split(',')
10         book1[content[0]] = content[1]
11 
12     # 另外一種方式,讀取另外一個文件,不須要close,會自動關閉
13     with open('book2.txt', 'r', encoding='UTF-8') as file2:
14         lines2 = file2.readlines()
15     for line in lines2:
16         line = line.strip()  # 去空白
17         content = line.split(',')
18         book2[content[0]] = content[1]

定義一個函數,用於合併內容,並保存。關鍵點以下所示:blog

  1. append 用於爲數組添加新元素。
  2. dict.keys函數 用於返回全部的key。
  3. join函數用於將數組轉換成字符串,並以對應字符分割。
  4. writelines 用於寫入全部的行到文件。
  5. with語法,當執行結束時,自動close,並釋放資源。
 1 def merge_book():
 2     """合併內容"""
 3     lines = []  # 定義一個空列表
 4     header = '姓名\t 電話\t 文本\n'
 5     lines.append(header)
 6     # 遍歷第一個字典
 7     for key in book1:
 8         line = ''
 9         if key in book2.keys():
10             line = line + '\t'.join([key, book1[key], book2[key]])
11             line += '\n'
12         else:
13             line = line + '\t'.join([key, book1[key], ' *****'])
14             line += '\n'
15         lines.append(line)
16     # 遍歷第2個,將不包含在第1個裏面的寫入
17     for key in book2:
18         line = ''
19         if key not in book1.keys():
20             line = line + '\t'.join([key, ' *****', book2[key]])
21             line += '\n'
22             lines.append(line)
23     # 寫入book3
24     with open('book3.txt', 'w', encoding='UTF-8') as f:
25         f.writelines(lines)

總體調用,以下所示:遞歸

1 if __name__ == '__main__':
2     # 讀取內容
3     read_book()
4     # 合併內容
5     merge_book()
6 
7     # print(book1)
8     # print(book2)

最後拼接後生成的文件,以下所示:ip

經過以上兩個例子,能夠大體瞭解文件及目錄操做的一些方法及步驟。

備註

西江月·夜行黃沙道中

[宋]辛棄疾

明月別枝驚鵲,清風半夜鳴蟬。稻花香裏說豐年,聽取蛙聲一片。 七八個星天外,兩三點雨山前。舊時茅店社林邊,路轉溪橋忽見。

相關文章
相關標籤/搜索