python —— 文件持久化存储

文件持久化存储

目录

文件持久化存储

脑图

文件的操作

with 语句

OS模块

json模块

存储为Excel文件


脑图

文件的操作

# 1. 打开文件
"""
mode:
    r: 只能读文件
    w: 只能写入(清空文件内容)
    a+: 读写(文件追加写入内容)
"""
f = open('doc/hello.txt',mode='a+')
# 2. 文件读写操作
f.write('java\n')
# 3. 关闭文件
f.close()

with 语句

"""
with语句:使用于对资源进行访问的场合,
    保证不管处理过程中是否发生错误或者异常都会自动执行规定的(“清理”)操作,
    释放被访问的资源。
"""
# ****with语句
with open('doc/test.txt', 'w+') as f:
    f.write('hello world\n') # 写入文件
    f.seek(0, 0)      # ****: 移动指针到文件最开始
    print("当前指针的位置:", f.tell())
    f.seek(0, 2)      # 移动指针到文件末尾
    print("当前指针的位置:", f.tell())
    print(f.read())         # 读取文件内容


OS模块

import  os
import platform
# 1. 获取操作系统类型
print(os.name)
# 2. 获取主机信息,windows系统使用platform模块, 如果是Linux系统使用os模块
"""
try: 可能出现报错的代码
excpt: 如果出现异常,执行的内容
finally:是否有异常,都会执行的内容
"""
try:
    uname = os.uname()
except Exception:
    uname = platform.uname()
finally:
    print(uname)

# 3.获取系统的环境变量
envs = os.environ
# os.environ.get('PASSWORD')
print(envs)

# 4. 目录名和文件名拼接
# os.path.dirname获取某个文件对应的目录名
# __file__当前文件
# join拼接, 将目录名和文件名拼接起来。
BASE_DIR = os.path.dirname(__file__)
setting_file = os.path.join(BASE_DIR, 'dev.conf')
print(setting_file)

json模块

import  json

# 1. 将python对象编码成json字符串
users = {'name':'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("存储成功")
print(json_str, type(json_str))

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

存储为Excel文件

import pandas
hosts = [
    {'host':'1.1.1.1', 'hostname':'test1', 'idc':'ali'},
    {'host':'1.1.1.2', 'hostname':'test2', 'idc':'ali'},
    {'host':'1.1.1.3', 'hostname':'test3', 'idc':'huawei'},
    {'host':'1.1.1.4', 'hostname':'test4', 'idc':'ali'}
]
# 1. 转换数据类型
df = pandas.DataFrame(hosts)
# print(df)

# 2. 存储到excel文件中
df.to_excel('doc/hosts.xlsx')
print('success')

"""
如何安装pandas?
> pip install pandas -i https://pypi.douban.com/simple
如何安装对excel操作的模块?
> pip install openpyxl -i https://pypi.douban.com/simple
"""



猜你喜欢

转载自blog.csdn.net/qq_47714288/article/details/113804020
今日推荐