Python 编程 | 连载 20 - 文件 I/O
一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第20天,点击查看活动详情。
一、文件的创建与写入
Python 可以通过内置函数 open() 获取文件对象,然后进行创建和读写操作,该内置函数返回一个文件对象
open(path, mode)
- path:文件路径
- mode:操作模式
mode 操作模式又分为写入模式和读模式,文件写入模式有以下几种:
- w:创建文件
- w+:创建文件并读取文件
- wb:二进制形式创建文件
- wb+:二进制形式创建或者追加内容
- a:追加内容
- a+:读写模式的追加
- ab:二进制形式的读写
- ab+:二进制形式读写追加
文件对象的写入操作方法:
方法 | 参数 | 描述 | 使用 | 返回 |
---|---|---|---|---|
write() | message | 写入内容 | f.write('hello') | int类型既写入字符的个数 |
writelines() | message_list | 批量写入 | f.writelines(['hello', 'python']) | 无返回值 |
close() | 无参数 | 关闭并保存文件 | f.close() | 无返回 |
plus:文件操作完成后必须执行close()函数,关闭文件对象
import os
file_path = os.path.join(os.getcwd(), "alpha.txt")
f = open(file_path, 'w')
res = f.write('Hello')
print('{}个字符被写入文件'.format(res))
f.close()
import os
file_path = os.path.join(os.getcwd(), "bravo.txt")
f = open(file_path, 'w+')
write_res = f.write('Hello')
print('{}个字符被写入文件'.format(write_res))
# 将光标设置到起始位置
f.seek(0)
read_res = f.read()
print(read_res, type(read_res))
f.close()
读取文件时,需要首先将光标设置到起始位置,否则读取到的内容为空。
import os
file_path = os.path.join(os.getcwd(), "charlie.txt")
f = open(file_path, 'ab')
message = 'Hallo'
_message = message.encode('utf-8')
write_res = f.write(_message)
print('{}个字符被写入文件'.format(write_res))
f.close()
import os
file_path = os.path.join(os.getcwd(), "delta.txt")
f = open(file_path, 'a+')
write_res_01 = f.write('Hi\n')
print('{}个字符被写入文件'.format(write_res_01))
write_res_02 = f.write('Hello\n')
print('{}个字符被写入文件'.format(write_res_02))
write_res_03 = f.write('Hallo\n')
print('{}个字符被写入文件'.format(write_res_03))
f.close()
import os
file_path = os.path.join(os.getcwd(), "delta.txt")
f = open(file_path, 'a')
message_list = ['stark', 'thor', 'banner', 'clint']
f.writelines(message_list)
f.close()
将写入内容改为
message_list = ['STARK\n', 'THOR\n', 'BANNER\n', 'CLINT\n']
新建 ops_pack.py 脚本,定义函数 create(),用于创建 python package
import os
import datetime
def create(path, name):
pack_path = os.path.join(path, name)
if os.path.exists(pack_path):
raise Exception('{}已经存在,不可重复创建'.format(path))
os.makedirs(pack_path)
init_file_path = os.path.join(pack_path, '__init__.py')
f = open(init_file_path, 'w')
now = datetime.datetime.now()
f.write('# Date: {}'.format(datetime.datetime.strftime(now, '%Y/%m/%d')))
f.close()
print('{} Python Package 创建完成'.format(name))
print('{} package是否存在: {}'.format(name, os.path.exists(pack_path)))
if __name__ == '__main__':
current = os.getcwd()
create(current, 'hotel')
hotel Python packate 被成功创建,并且在 __init__.py文件中的第一行加上了时间注释。
定义一个对象,用来创建文件并写入内容。
class OpenWrite:
def __init__(self, path, name, mode='w', is_return=True):
self.path = path
self.name = name
self.mode = mode
self.is_return = is_return
def write(self, message):
# 将路径和要创建的文件合并
path = os.path.join(self.path, self.name)
f = open(path, mode=self.mode)
if self.is_return:
message = "%s\n" % message
f.write(message)
f.close()
if __name__ == '__main__':
o = OpenWrite(os.getcwd(), 'iris.txt')
o.write('thor')
iris_file = os.path.join(os.getcwd(), 'iris.txt')
print('iris.txt文件是否存在:{}'.format(os.path.exists(iris_file)))
控制台输出文件已存在,被成功创建
指定内容也被成功写入
二、文件的读取
读取模式有两种:
- r:读取文件
- rb:二进制形式读取文件,列表元组字典需要通过二进制形式写入文件中
文件对象的读方法如下:
方法或属性 | 参数 | 方法描述 | 使用 |
---|---|---|---|
read() | 无 | 返回整个文件字符串 | f.read() |
readlines() | 无 | 返回每一行字符串的列表 | f.readlines() |
readline() | 无 | 返回文件中一行内容 | f.readline() |
mode | 无 | 返回文件操作模式 | f.mode |
name | 无 | 返回文件名 | f.name |
closed | 无 | 文件是否关闭 | f.colsed |
plus:文件操作完成后必须执行close()函数,关闭文件对象
f = open('iris.txt', 'r')
content = f.read()
f.close()
print('iris.txt文件中的内容为:{}'.format(content))
print('iris.txt文件中的内容的长度为:{}'.format(len(content)))
print('iris.txt文件中的内容的类型为:{}'.format(type(content)))
f = open('iris.txt', 'r')
content = f.readlines()
f.close()
print('iris.txt文件中的内容为:{}'.format(content))
print('iris.txt文件中的内容的长度为:{}'.format(len(content)))
print('iris.txt文件中的内容的类型为:{}'.format(type(content)))
# 循环content 列表
for c in content:
print(c)
f = open('iris.txt', 'r')
content_01 = f.readline()
print('读取到第一行的内容为:{}'.format(content_01))
content_02 = f.readline()
print('读取到第二行的内容为:{}'.format(content_02))
print('第二行内容的长度为:{}'.format(len(content_02)))
print('第二行内容的类型为:{}'.format(type(content_02)))
f.close()
print('{}文件的操作模式为{},是否关闭{}'.format(f.name, f.mode, f.closed))
控制台输出stark字符的长度为6,这是应为在文件中还包含了换行符,既'stark\n'的长度为6,控制台直接将\n变成换行符展示出来了。
每次对文件进行操作完成之后都必须要执行close()函数来关闭对象,使用with关键字进行文件操作可以不用在显示的调用close()函数关闭文件对象,只要是在with代码块中文件对象都不会被关闭,出了with代码块文件对象就会被关闭。
with open('iris.txt', 'r') as f:
content_01 = f.readline()
print('读取到第一行的内容为:{}'.format(content_01))
content_02 = f.readline()
print('读取到第二行的内容为:{}'.format(content_02))
print('第二行内容的长度为:{}'.format(len(content_02)))
print('第二行内容的类型为:{}'.format(type(content_02)))
# f.close()
print('{}文件的操作模式为{},是否关闭{}'.format(f.name, f.mode, f.closed))
print('{}文件的操作模式为{},是否关闭{}'.format(f.name, f.mode, f.closed))
with代码块内调用closed属性返回False既未关闭,with代码块外调用closed属性返回True既文件被关闭。
创建Read对象,封装读文件的方法
import os
class Read:
def __init__(self, path, name, mode):
self.path = path
self.name = name
self.mode = mode
def read(self):
file = os.path.join(self.path, self.name)
with open(file, self.mode) as f:
content = f.read()
return content
def readline(self):
content_list = []
file = os.path.join(self.path, self.name)
with open(file, self.mode) as f:
while True:
content = f.readline()
content_list.append(content)
if len(content) == 0:
break
return content_list
def readlines(self):
file = os.path.join(self.path, self.name)
with open(file, self.mode) as f:
content_list = f.readlines()
return content_list
if __name__ == '__main__':
r = Read(os.getcwd(), 'iris.txt', 'r')
print(r.read())
print(r.readline())
print(r.readlines())
三、YAML 配置文件读取
yaml 是一种配置文件格式,以 yaml 或者 yml 结尾,该配置文件格式如下:
name:
stark
address:
new york
pets:
- dog
- cat
- wolf
Python 中读取 yml 格式文件的第三方模块是 pyyaml,通过 pip 命令安装。
pip3 install pyyaml -i https://pypi.tuna.tsinghua.edu.cn/simple
首先新建一个 info.yaml 文件,添加以下内容:
name:
stark
suits:
- mark0
- mark1
- mark2
- mark3
- mark5
friend:
nickname: peter
创建 yaml_read.py文件,定义函数读取 info.yaml
import yaml
def read_yaml(path):
with open(path, 'r') as f:
data = f.read()
res = yaml.load(data, Loader=yaml.FullLoader)
return res
if __name__ == '__main__':
res = read_yaml('info.yaml')
print(res)
相关文章
- Python 编程 | 连载 25 - Python 多进程
- Python 编程 | 连载 05 - 字符串操作
- Python 编程 | 连载 21 -序列化与加密模块
- Python 编程 | 连载 02 - 数字与字符串
- Python 编程骚操作连载(一)- 字符串、列表、字典和集合的处理(Part A)
- Python 编程 | 连载 08 - 列表与元组操作
- macbookpro安装anaconda_mac下python编程软件
- Python 编程 | 连载 07 - 列表与元组操作
- Python 编程 | 连载 22 - logging 与 random 模块
- 常用Python库_编程代码大全
- Python Flask 编程 | 连载 05 - Jinja2 模板引擎
- Python 编程 | 连载 06 - 格式化与转义字符
- Python 编程骚操作连载(二)- 类与对象
- Python 编程 | 连载 11 - Python 集合
- Python 编程 | 连载 15 - Python 的类
- PyCharm下使用 ipython 交互式编程「建议收藏」
- Python基础21-网络编程
- Python 编程 | 连载 20 - 文件 I/O
- Python 编程 | 连载 09 - 列表、元组和字符串切片
- Python Flask 编程 | 连载 08 - Jinja2 过滤器