NipGeihou's blog NipGeihou's blog
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档

NipGeihou

我见青山多妩媚,料青山见我应如是
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档
  • 教程

    • 安装
    • 流程控制与定义函数
    • 数据结构(类型)
    • 模块
    • 输入与输出
      • 输入与输出
        • 输出
        • 格式化字符串字面值(f)
        • str.format()
      • 输入
        • input
        • 读写文件
        • 读取方法
        • 写入方法
        • 使用 json 保存结构化数据
    • 错误与异常
    • 类
    • 标准库
    • 虚拟环境和包
    • 开发环境
    • ORM - SQLAlchemy
  • Python
  • 教程
NipGeihou
2024-10-11
目录

输入与输出

# 输入与输出

# 输出

# 格式化字符串字面值 (f)

要在字符串开头的 引号 / 三引号 前添加 f 或 F 。在这种字符串中,可以在 { 和 } 字符之间输入引用的变量:

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'

或字面值的 Python 表达式:

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.') # 将 pi 舍入到小数点后三位
The value of pi is approximately 3.142.

# 在 ':' 后传递整数,为该字段设置最小字符宽度,常用于列对齐:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

还有一些修饰符可以在格式化前转换值。 '!a' 应用 ascii() (opens new window) , '!s' 应用 str() (opens new window), '!r' 应用 repr() (opens new window):

>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.

= 说明符可被用于将一个表达式扩展为 表达式文本=表达式值 的形式。

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'

# str.format()

>>> yes_votes = 42_572_654
>>> total_votes = 85_705_149
>>> percentage = yes_votes / total_votes
>>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes  49.67%'


# 基本用法
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

# 定义索引
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

# 关键字参数
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

# 混合写法
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
...                                                    other='Georg'))
The story of Bill, Manfred, and Georg.

最佳实践

# 用方括号 '[]' 访问键来完成
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

# 采用 ** 标记的关键字参数传入
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

# 输入

# input

接受用户输入

>>> x = input()
# 此处阻塞等待用户输入

>>> x = input("请输入金额:")
# 此处阻塞等待用户输入

# 读写文件

# open(filename, mode, encoding=None),返回 file object
>>> f = open('workfile', 'w', encoding="utf-8")
  • 第一个实参是文件名字符串。
  • 第二个实参是包含描述文件使用方式字符的字符串。mode 的值包括
    • 'r' ,表示文件只能读取;
    • 'w' 表示只能写入(现有同名文件会被覆盖);
    • 'a' 表示打开文件并追加内容,任何写入的数据会自动添加到文件末尾。
    • 'r+' 表示打开文件进行读写。
    • mode 实参是可选的,省略时的默认值为 'r' 。

在处理文件对象时,最好使用 with (opens new window) 关键字。优点是,子句体结束后,文件会正确关闭,即便触发异常也可以。而且,使用 with 相比等效的 try (opens new window)-finally (opens new window) 代码块要简短得多:

>>> with open('workfile', encoding="utf-8") as f:
...     read_data = f.read()

>>> # 我们可以检测文件是否已被自动关闭。
>>> f.closed
True

# 读取方法

# f.read(size) 
# 省略 size 或为负数时,读取并返回整个文件的内容;文件大小是内存的两倍时,会出现问题。
# size 取其他值时,读取并返回最多 size 个字符(文本模式)或 size 个字节(二进制模式)。
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

# f.readline() 从文件中读取单行数据;字符串末尾保留换行符(\n),只有在文件不以换行符结尾时,文件的最后一行才会省略换行符。
# 只要 f.readline() 返回空字符串,就表示已经到达了文件末尾,空行使用 '\n' 表示,该字符串只包含一个换行符。
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''

# 读取多行最佳实践
>>> for line in f:
...     print(line, end='')
... 
This is the first line of the file.
Second line of the file

# 写入方法

# 把 string 的内容写入文件,并返回写入的字符数。
>>> f.write('This is a test\n')
15

# 写入其他类型的对象前,要先把它们转化为字符串(文本模式)或字节对象(二进制模式)
>>> value = ('the answer', 42)
>>> s = str(value)  # 将元组转换为字符串
>>> f.write(s)
18

# f.seek(offset, whence) 可以改变文件对象的位置。
# 通过向参考点添加 offset 计算位置;参考点由 whence 参数指定。 whence 值为 0 时,表示从文件开头计算,1 表示使用当前文件位置,2 表示使用文件末尾作为参考点。省略 whence 时,其默认值为 0,即使用文件开头作为参考点。
>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # 定位到文件中的第 6 个字节
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # 定位到倒数第 3 个字节
13
>>> f.read(1)
b'd'

# 使用 json 保存结构化数据

>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'

# 以json格式写入f
json.dump(x, f)
# 读取f转为x
x = json.load(f)
上次更新: 2024/10/12, 00:46:36
模块
错误与异常

← 模块 错误与异常→

最近更新
01
iSCSI服务搭建
05-10
02
磁盘管理与文件系统
05-02
03
网络测试 - iperf3
05-02
更多文章>
Theme by Vdoing | Copyright © 2018-2025 NipGeihou | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式