5.1 Python3 进阶 - 文件操作
>>返回主目录
源码
# open() 函数
# 打开文件方式一
fp = open('demo/open_mode', 'r', encoding='utf-8')
print('查看返回对象:', fp)
print('文件是否关闭:', fp.closed)
print('文件的访问模式:', fp.mode)
print('文件名称:', fp.name)
# close()方法:关闭一个已打开的文件,例如:
fp.close()
print('再次查看文件是否关闭:', fp.closed)
# 打开文件方式二:上下文管理机制,with语法
with open('demo/open_mode', 'r', encoding='utf-8') as fp: # 必须是个可迭代对象,支持上下文
print('文件是否关闭:', fp.closed)
print('再次查看文件是否关闭:', fp.closed)
# with支持同时对多个文件的上下文进行管理
with open('demo/open_mode') as fp1, open('demo/file_object_function.txt') as fp2:
print('同时打开两个文件::', fp1, fp2)
源码
from typing import Iterator
# close()方法
fp = open('demo/open_mode', 'r', encoding='utf-8')
fp.close()
fp.close()
print('属性仍然可以被访问:', fp.name)
# next()方法
with open('demo/file_object_function.txt', 'r', encoding='utf-8') as fp:
print(next(fp))
print(fp.__next__())
print(next(fp))
print('判断fp对象是否是迭代器:', isinstance(fp, Iterator))
源码
# read()方法
with open('demo/file_object_function.txt', 'r', encoding='utf-8') as fp:
# print('读取12字节数字符:', fp.read(12))
print('读取所有字节数:', fp.read())
# readline()方法
with open('demo/file_object_function.txt', 'r', encoding='utf-8') as fp:
# print('读取50字节数字符:', fp.readline(50))
print('读取整行所有字节数:', fp.readline())
源码
# readlines()方法
with open('demo/file_object_function.txt', 'r', encoding='utf-8') as fp:
# print('读取30字节数字符:', fp.readlines(30))
print('读取整行所有字节数:', fp.readlines())
# 可通过for循环进行迭代
with open('demo/file_object_function.txt', 'r', encoding='utf-8') as fp:
for n, line in enumerate(fp.readlines()):
print(f'第{n}行是:', line)
源码
# write()方法:文件打开模式:r+(读写,文件指针将会放在文件的开头)
with open('demo/write_mode_r+', 'r+', encoding='utf-8') as fp:
# print(fp.read()) # 先读后写
print('返回值是:', fp.write('5test write\n'))
fp.write('6test write\n')
# print(fp.read()) # 先写后读
# 文件打开模式:w+(读写)
with open('demo/write_mode_w+', 'w+', encoding='utf-8') as fp:
# print(fp.read()) # 先读后写
fp.write('5test write\n')
fp.write('6test write\n')
print(fp.read()) # 先写后读
# 文件打开模式:w(只写)
with open('demo/write_mode_w-', 'w') as fp:
# print(fp.read()) # 先读后写,读文件报错
fp.write('1test write\n')
源码
# 文writelines()方法:件打开模式:w(只写)
with open('demo/write_mode_w', 'w') as fp:
seq1 = ['We', 'are', 'learning', 'writelines', 'function!']
seq2 = ['\nI', '\nam', '\nfighting!']
fp.writelines(seq1)
fp.writelines(seq2)
# 文件打开模式:a+(读写,文件指针会放在文件的末尾)
with open('demo/write_mode_a+', 'a+') as fp:
seq = ['We', 'are', 'learning', 'writelines', 'function!\n']
fp.writelines(seq)
源码
"""
.env文件内容如下
# test1
key1=value1
key2 = value2=
key3 = 'value3='
key4 ="val/ue4="
# test2
key5 =
key6 = ''
{'key7': 'key7'}
{'key7': 'key7', 'key8': 'key8', 'key9': 'key9'}
key7=key7
key8=key8
key9=key9
"""
# Author:PortosHan
# Datetime:2021/8/24 18:24
# Project:zbcf_python_test_project
"""
功能
1、读取配置文件信息;
2、根据配置文件中key键获取value值;
3、添加配置信息:key=value;
"""
from functools import partial
def get_env_info(path):
"""
:function: 读取env文件内容
:param path: 传入文件路径名称
:return:
"""
with open(path) as fp:
print(fp.read())
def get_env_value(path, key=None):
"""
:function: 根据key获取value值
:param path: 传入文件路径名称
:param key: 传入key键
:return: 返回value值
"""
value = None
if key:
file_key_value = {}
with open(path) as fp:
lines = fp.readlines()
strip_lines = list(map(lambda x: x.replace('\n', ''), lines))
for line in strip_lines:
if not line.strip().startswith('#') and '=' in line:
line_key, line_value = line.split('=', 1)
line_key = line_key.strip()
line_value = line_value.strip().strip("\"'")
file_key_value[line_key] = line_value
# print(file_key_value)
value = file_key_value[key]
print(f'{key}的值是:{value}')
return value
def set_key_value(path, **kwargs):
"""
:function: 向.env文件中添加key=value形式的数据(默认是追加)
:param path: 传入文件路径名称
:param kwargs: 可传入字典类型的值
:return:
"""
for key, value in kwargs.items():
key_value = key + '=' + value
with open(path, 'a') as fp:
fp.write('\n' + key_value)
if __name__ == '__main__':
# .env配置文件地址(相对路径)
env_path = 'exercise_1/.env'
# 1、读取配置文件信息;
get_env_info(env_path)
# 2、根据配置文件中key键获取value值;
get_env_value(env_path, 'key4')
# 利用偏函数,固定env_path的值
get_partial_env_value = partial(get_env_value, env_path)
get_partial_env_value('key4')
# 3、添加配置信息:key=value;
set_key_value(env_path, key7='key7', **{'key8': 'key8', 'key9': 'key9'})
>>返回主目录
作者: PortosHan
出处: https://www.cnblogs.com/PortosHan/
关于作者:专注于软件测试、测试开发等领域,请多多赐教!
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。 原文链接 如有问题,可邮件(bhanzdan@163.com)咨询。