python虽强大,但偶尔使用,每次总是忘记常用api,总是翻以前写的例子,因此记录,以后每次翻这里;
1、遍历目录
import os
dir = r'D:\doc\excel_pandas'
for lists in os.listdir(dir):
if lists.endswith('.py'):
print(lists)
print(os.path.join(dir, lists))
2、遍历目录和子目录
import os
dir = r'D:\Data\pic'
for home, dirs, files in os.walk(dir):
for file in files:
if file.endswith('.jpg'):
print(file)
print(os.path.join(home, file))
3、读取文件(一行行)
txtFile = r'D:\Lzc\vs2019\project\3Dmeasure\src-test\rslt\1210_shot_30mm_blue-show.txt'
with open(txtFile, 'r') as f:
for line in f:
print(line)
4、写文件
txtFile = r'D:\doc\excel_pandas\test.txt'
with open(txtFile, 'w') as f:
f.writelines('l\n')
f.writelines('z\n')
f.writelines('c\n')
f.writelines('是\n')
f.writelines('帅\n')
f.writelines('哥\n')
5、读json
import json
jsonFile = r'D:\Lzc\vs2019\project\3Dmeasure\src-test\rslt\1210_shot_30mm_blue-show.json'
with open(jsonFile, 'r') as f:
json_load = json.load(f)
if "human_centroid_offset_val" in json_load:
print(json_load["human_centroid_offset_val"])
其中1210_shot_30mm_blue-show.json内容是:
{"human_centroid_offset_val":"20.348019","legs_length_diff_val":"0.000000","neck_extension_angle":"57.573189","pelvic_inclination_angle":"-10.480483","pelvic_roll_diff_val":"0.000000","shoulders_diff_val":"0.000488","thoracic_kyphosis_angle":"38.073639"}
6、写json
from collections import defaultdict, OrderedDict
import json
jsonFile = r'D:\doc\excel_pandas\test.json'
json_dict = OrderedDict()#defaultdict全部数据写在一行,OrderedDict数据有序排列
json_dict['image_name'] = 'test.jpg'
json_dict['image_w'] = 640
json_dict['image_h'] = 480
json_str = json.dumps(json_dict, indent=2)#defaultdict模式下就不应该有indent参数,OrderedDict模式下表示缩进,每行缩进多少个字符
with open(jsonFile, 'w') as f:
f.write(json_str)
7、读excel(.xlsx文件)
import pandas as pd
xlsxFile = r'D:\doc\excel_pandas\test.xlsx'
data = pd.read_excel(xlsxFile)
print(data.values)#查看所有的值
print(data.values[0])#查看第一行的值
print(data['姓名'].values)#查看某一列所有的值
8、写excel(.xlsx文件)
import pandas as pd
xlsxFile = r'D:\doc\excel_pandas\test.xlsx'
dict = {'姓名': ['张三', '李四'],
'分数': [80, 90]}
df = pd.DataFrame(dict)
df.to_excel(xlsxFile, index=False)
9、修改excel(.xlsx文件)
import pandas as pd
xlsxFile1 = r'D:\doc\excel_pandas\test.xlsx'
xlsxFile2 = r'D:\doc\excel_pandas\test2.xlsx'
data = pd.read_excel(xlsxFile1)
print(data.values)#查看所有的值
data['性别'] = None#新增列
data.loc[2] = ['王五', 100, '男']#新增行
data = data.drop([0, 2], axis=0)#删除多行,这里[0,2]并不是0-2行,而是0和2行:axis=0
data = data.drop(['分数', '性别'], axis=1)#删除多列:axis=1
pd.DataFrame(data).to_excel(xlsxFile2, sheet_name='Sheet1', index=False, header=True)#保存
|