Python之文件与模块

一、文件

1.文件的基本操做

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

2.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())         # 读取文件内容

使用with语句可以不需要手动关闭文件
执行如下:
在这里插入图片描述

3.存储为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
"""

执行如下:
在这里插入图片描述
在这里插入图片描述

二、模块

1.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)

2.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))

执行如下:
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/nk298120/article/details/113847954