Python 编程 | 连载 20 - 文件 I/O

简介: Python 编程 | 连载 20 - 文件 I/O

一、文件的创建与写入

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()
复制代码

3dbaa20cd25c4f5c8d2bbcf7fa9b4a5c_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

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()
复制代码

0921eb5f13734de9842d2151dba78689_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

读取文件时,需要首先将光标设置到起始位置,否则读取到的内容为空。

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()
复制代码

75ffb279139645cdbcfdc037eb6064a9_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

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()
复制代码

6f493559f2ac4805a1877524f7fe3f0d_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

cc16032df1334ab48711288f617d1348_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

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()
复制代码

cf2a83e090f94d46995a372099051906_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

将写入内容改为

message_list = ['STARK\n', 'THOR\n', 'BANNER\n', 'CLINT\n']
复制代码

c7537cd79be54efa8b6bf7447fa3e258_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

新建 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')
复制代码

03a73c3d9bdf4ddbbba04db5bd99aafa_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

a7bf594551d846fda74c3ecd903ff149_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

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)))
复制代码

59da31d5542d4be2a21e514f184ca1da_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

控制台输出文件已存在,被成功创建

55d38bed65e848c08e8bc3c679a123ea_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

指定内容也被成功写入

二、文件的读取

读取模式有两种:

  • 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)))
复制代码

7debeae6c8b0453dab5b0392730123cf_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

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)
复制代码

f8295338bb93458ca60e2a38a7cea548_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

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))
复制代码

56f145e4d20d488d8ce49d9daed3a09e_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

控制台输出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))
复制代码

94099942a45a441caf4caa662615aaf8_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

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())
复制代码

f166a51f71eb467eadd93fde61fc91ea_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

三、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)
复制代码

5a18094959a94b8b99471d154ba81941_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.png

相关文章
|
10小时前
|
Python
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存在,该函数对路径进行检查,存在则返回True,不存在则返回False。示例代码展示了如何检查'example.txt'文件是否存在并相应打印消息。此外,`os.path.isfile()`用于确认路径是否为文件,仅当是文件时返回True,否则返回False,同样配以示例说明其用法。
7 2
|
2天前
|
Shell Python
Python Stock guess_indicators_daily_job.py文件的调整
Python Stock guess_indicators_daily_job.py文件的调整
12 1
|
2天前
|
XML 前端开发 数据格式
BeautifulSoup 是一个 Python 库,用于从 HTML 和 XML 文件中提取数据
BeautifulSoup 是 Python 的一个库,用于解析 HTML 和 XML 文件,即使在格式不规范的情况下也能有效工作。通过创建 BeautifulSoup 对象并使用方法如 find_all 和 get,可以方便地提取和查找文档中的信息。以下是一段示例代码,展示如何安装库、解析 HTML 数据以及打印段落、链接和特定类名的元素。BeautifulSoup 还支持更复杂的查询和文档修改功能。
9 1
|
3天前
|
JSON 数据格式 开发者
pip和requests在Python编程中各自扮演着不同的角色
`pip`是Python的包管理器,用于安装、升级和管理PyPI上的包;`requests`是一个HTTP库,简化了HTTP通信,支持各种HTTP请求类型及数据交互。两者在Python环境中分别负责包管理和网络请求。
16 5
|
4天前
|
数据采集 NoSQL 中间件
python-scrapy框架(四)settings.py文件的用法详解实例
python-scrapy框架(四)settings.py文件的用法详解实例
9 0
|
4天前
|
存储 数据采集 数据库
python-scrapy框架(三)Pipeline文件的用法讲解
python-scrapy框架(三)Pipeline文件的用法讲解
7 0
|
6天前
|
缓存 数据处理 Python
python读取文件到缓存
python读取文件到缓存
11 1
|
6天前
|
存储 Python 容器
Python高级编程
Python集合包括可变的set和不可变的frozenset,用于存储无序、不重复的哈希元素。创建集合可使用{}或set(),如`my_set = {1, 2, 3, 4, 5}`。通过add()添加元素,remove()或discard()删除元素,如`my_set.remove(3)`。
|
6天前
|
存储 数据挖掘 Python
Python技术分享:实现选择文件或目录路径的方法
Python技术分享:实现选择文件或目录路径的方法
16 2
|
7天前
|
测试技术 Python
Python模块化方式编程实践
Python模块化编程提升代码质量,包括:定义专注单一任务的模块;使用`import`导入模块;封装函数和类,明确命名便于重用;避免全局变量降低耦合;使用文档字符串增强可读性;为每个模块写单元测试确保正确性;重用模块作为库;定期维护更新以适应Python新版本。遵循这些实践,可提高代码可读性、重用性和可维护性。
28 2