Python之文件与模块(打开、读写、关闭文件;with语句,存储为excel文件,os模块、json模块详解)

1、文件的基本操作

打开、读写、关闭文件

在python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件。
open(文件名,访问模式) e.g. f = open(‘test.txt’, ‘w’)
如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

"""
mode:
    r: 只能读文件
    w: 只能写入(清空文件内容)
    a+: 读写(文件追加写入内容)
"""
# f = open('doc/hello.txt')
# print(f.read())
# f.close()

f = open('doc/hello.txt', mode='a+')

# 2. 文件读写操作
f.write('java\n')

# 3. 关闭文件
f.close()

在这里插入图片描述

在这里插入图片描述

2、with语句

seek(offset, from)有2个参数: offset:偏移量 from:方向
0:表示文件开头;
1:表示当前位置;
2:表示文件末尾

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

在这里插入图片描述
在这里插入图片描述

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
"""

在这里插入图片描述
在这里插入图片描述

3、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')
# envs = os.environ
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)
# with open(setting_file, 'w') as f:
#     pass

在这里插入图片描述

4、json模块详解

将python对象编码成json字符串
将json字符串解码成python对象
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/weixin_45777669/article/details/113992195