python (eight) --os, json module

1. Exception catch

##异常捕获
"""
try:可能出现报错的代码
except:如果出现异常,执行的内容
finally:最终都会执行的内容
"""
try:
    uname = os.uname()
except Exception:
    uname = platform.uname()
finally:
    print(uname)

2. os module

#1.获取主机信息
import os
import platform
print(os.name)
#print(os.uname)
#获取主机信息,windows系统使用platform,linux使用os模块
print(platform.uname())

# 3. 获取系统环境变量
envs = os.environ
#os.environ.get('PASSWORD')从环境变量里面获取某种特殊变量值
#os.getenv('PASSWORD')
print(envs)

#4.path
os.path

#5.目录名和文件名拼接
#os.path.dirname 获取某个文件对应的目录名
#__file__当前文件
#join拼接,将目录名和文件名拼接起来。
#rename(需要修改的文件名, 新的文件名)
BASE_DIR = os.path.dirname(__file__)
print(BASE_DIR)   #D:/pycharm pro/项目存储/2-6 内置数据结构3
setting_file = os.path.join(BASE_DIR,'dev.conf')
new_file = os.rename('hello.txt','hello1.txt')
os.remove('hello1.txt')
print(setting_file)

#6.创建目录和删除目录
os.makedirs()
os.mkdir()
os.rmdir()

#7. 创建文件删除文件
os.mknod('hello.txt')
os.remove('hello.txt')

#8.判断文件或者目录是否存在
os.path.exists('hello.txt')

#9.分离后缀名和文件名
os.path.splitext('hello1.txt')
os.path.split('hello1.txt')

#10.将目录名和文件名分离
os.path.split('D:/pycharm pro/项目存储/2-6 内置数据结构3')

3.json module

-	 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 

	JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、Java、JavaScript、Perl、Python等)。
	
	这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, 
	allow_nan=True, cls=None, indent=None, separators=None, 
	encoding="utf-8", default=None, sort_keys=False, **kw)
# ensure_ascii=False: 中文存储需要设定
# indent=4: 增加缩进,增强可读性,但缩进空格会使数据变大
# separators=(',',':'): 自定义分隔符,元素间分隔符为逗号, 字典key和value值的分隔符为冒号
# sort_keys=True: 字典排序

import  json
#1.将python对象编码成json字符串
users = {
    
    'user1':'westos',"age":18,"city":"西安"}
json_str = json.dumps(users)
with open('doc/hello.json','w') as f:
    #ensure_ascii=False 中文可以存储成功
    #indent=4缩进为4个空格
    json.dump(users,f,ensure_ascii=False,indent=4)
print(json_str,type(json_str))

#2.将json字符串解码成python对象
with open('doc/hello.json') as f:
    python_obj = json.load(f)
    print(python_obj)

3.2 Save as exce file (pandas)

pandas as the core of data cleaning


import pandas,openpyxl
hosts = [
    {
    
    'host':'1.1.1.1','hostname':'test1','idc':'aliyun'},
    {
    
    'host':'1.1.1.2','hostname':'test2','idc':'aliyun'},
    {
    
    'host':'1.1.1.3','hostname':'test3','idc':'aliyun'},
    {
    
    'host':'1.1.1.4','hostname':'test4','idc':'aliyun'}
]
#1.转换数据类型
df = pandas.DataFrame(hosts)
print(df)
#2.存储到excel文件中
df.to_excel('hosts.xlsx')
print('succerss')

#结果
      host hostname     idc
0  1.1.1.1    test1  aliyun
1  1.1.1.2    test2  aliyun
2  1.1.1.3    test3  aliyun
3  1.1.1.4    test4  aliyun
success
#生成下图的excel文件

Insert picture description here

Guess you like

Origin blog.csdn.net/qwerty1372431588/article/details/113727795