栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 常用功能

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 常用功能

python虽强大,但偶尔使用,每次总是忘记常用api,总是翻以前写的例子,因此记录,以后每次翻这里;

1、遍历目录

import os

dir = r'D:docexcel_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:Datapic'

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:Lzcvs2019project3Dmeasuresrc-testrslt1210_shot_30mm_blue-show.txt'

with open(txtFile, 'r') as f:
    for line in f:
        print(line)

4、写文件

txtFile = r'D:docexcel_pandastest.txt'

with open(txtFile, 'w') as f:
    f.writelines('ln')
    f.writelines('zn')
    f.writelines('cn')
    f.writelines('是n')
    f.writelines('帅n')
    f.writelines('哥n')

5、读json

import json

jsonFile = r'D:Lzcvs2019project3Dmeasuresrc-testrslt1210_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:docexcel_pandastest.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:docexcel_pandastest.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:docexcel_pandastest.xlsx'

dict = {'姓名': ['张三', '李四'],
        '分数': [80, 90]}
df = pd.Dataframe(dict)
df.to_excel(xlsxFile, index=False)

9、修改excel(.xlsx文件)

import pandas as pd

xlsxFile1 = r'D:docexcel_pandastest.xlsx'
xlsxFile2 = r'D:docexcel_pandastest2.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)#保存

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/689115.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号