Python 常用的操作檔案程式碼
阿新 • • 發佈:2020-07-16
1:統計list中相同的個數,並按大小排序。
original_list = ['a', 'b', 'b', 'a', 'd', 'd', 'b', 'z', 'c', 'b', 'r', 's', 'h', 'f', 'f', 's', 'b', 'b', 'y', 'b'] counter = {} for i in original_list: if original_list.count(i) > 1: counter[i] = original_list.count(i) # 按字典的值,進行從大到排序 counter_list = list(zip(counter.values(), counter.keys())) counter1_list= sorted(counter_list, reverse=True) # # 按字典的鍵,進行從大到排序 # counter1 = sorted(counter.items(), key=lambda x: x[0], reverse=True) for counter1 in counter1_list: print(counter1)
2:讀取excel中某一個sheet中的每一行資料。
import xlrd excel_path = r'********' data = xlrd.open_workbook(excel_path).sheet_by_name("sheet1") n_rows = data.nrows # 行數 for i in range(0, n_rows): # 每一行資料 row_values = data.row_values(i) print(row_values)
3:儲存資料到excel。
import pandas as pd dict_content_list = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}] data = pd.DataFrame(dict_content_list) data.to_excel('./***.xls', encoding='utf8', index=False)