前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 编程 | 连载 20 - 文件 I/O

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

作者头像
RiemannHypothesis
发布2022-09-26 15:41:07
2690
发布2022-09-26 15:41:07
举报
文章被收录于专栏:Elixir

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第20天,点击查看活动详情

一、文件的创建与写入

Python 可以通过内置函数 open() 获取文件对象,然后进行创建和读写操作,该内置函数返回一个文件对象

代码语言:javascript
复制
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()函数,关闭文件对象

代码语言:javascript
复制
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()
image.png
image.png
代码语言:javascript
复制
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()
image.png
image.png

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

代码语言:javascript
复制
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()
image.png
image.png
代码语言:javascript
复制
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()
image.png
image.png
image.png
image.png
代码语言:javascript
复制
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()
image.png
image.png

将写入内容改为

代码语言:javascript
复制
message_list = ['STARK\n', 'THOR\n', 'BANNER\n', 'CLINT\n']
image.png
image.png

新建 ops_pack.py 脚本,定义函数 create(),用于创建 python package

代码语言:javascript
复制
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')
image.png
image.png
image.png
image.png

hotel Python packate 被成功创建,并且在 __init__.py文件中的第一行加上了时间注释。

定义一个对象,用来创建文件并写入内容。

代码语言:javascript
复制
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)))
image.png
image.png

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

image.png
image.png

指定内容也被成功写入

二、文件的读取

读取模式有两种:

  • r:读取文件
  • rb:二进制形式读取文件,列表元组字典需要通过二进制形式写入文件中

文件对象的读方法如下:

方法或属性

参数

方法描述

使用

read()

返回整个文件字符串

f.read()

readlines()

返回每一行字符串的列表

f.readlines()

readline()

返回文件中一行内容

f.readline()

mode

返回文件操作模式

f.mode

name

返回文件名

f.name

closed

文件是否关闭

f.colsed

plus:文件操作完成后必须执行close()函数,关闭文件对象

代码语言:javascript
复制
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)))
image.png
image.png
代码语言:javascript
复制
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)
image.png
image.png
代码语言:javascript
复制
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))
image.png
image.png

控制台输出stark字符的长度为6,这是应为在文件中还包含了换行符,既'stark\n'的长度为6,控制台直接将\n变成换行符展示出来了。

每次对文件进行操作完成之后都必须要执行close()函数来关闭对象,使用with关键字进行文件操作可以不用在显示的调用close()函数关闭文件对象,只要是在with代码块中文件对象都不会被关闭,出了with代码块文件对象就会被关闭。

代码语言:javascript
复制
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))
image.png
image.png

with代码块内调用closed属性返回False既未关闭,with代码块外调用closed属性返回True既文件被关闭。

创建Read对象,封装读文件的方法

代码语言:javascript
复制
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())
image.png
image.png

三、YAML 配置文件读取

yaml 是一种配置文件格式,以 yaml 或者 yml 结尾,该配置文件格式如下:

代码语言:javascript
复制
name: 
    stark
address:
    new york
pets:
    - dog
    - cat
    - wolf

Python 中读取 yml 格式文件的第三方模块是 pyyaml,通过 pip 命令安装。

代码语言:javascript
复制
pip3 install pyyaml -i https://pypi.tuna.tsinghua.edu.cn/simple

首先新建一个 info.yaml 文件,添加以下内容:

代码语言:javascript
复制
name:
  stark
suits:
  - mark0
  - mark1
  - mark2
  - mark3
  - mark5
friend:
  nickname: peter

创建 yaml_read.py文件,定义函数读取 info.yaml

代码语言:javascript
复制
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)
image.png
image.png
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、文件的创建与写入
  • 二、文件的读取
  • 三、YAML 配置文件读取
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档