python学习总结7 - 输入与输出【格式化字符串及读写文件】

输入与输出

程序的输出有几种显示方式:

  1. 输出供人阅读的形式
  2. 也可以写入文件备用

1、更复杂的输出格式

写入值的方法:使用文件对象的 write() 方法;标准输出文件称为 sys.stdout

  • 使用 格式化字符串字面值,
  • 字符串的 str.format() 方法需要更多手动操作
  • 还可以用字符串切片和合并操作完成字符串处理操作
  • 函数 repr()str()
  • string 模块包含 Template 类,提供了将值替换为字符串的另一种方法。该类使用 $x 占位符,并用字典的值进行替换,但对格式控制的支持比较有限。
year = 2016
event = 'Referendum'
a = f'Results of the {year} {event}'
print(a)  # Results of the 2016 Referendum

yes_votes = 42_572_654
no_votes = 43_132_495
percentage = yes_votes / (yes_votes + no_votes)
a1 = '{:-9} YES votes  {:2.2%}'.format(yes_votes, no_votes)
print(a1)  # 42572654 YES votes  4313249500.00%

1.1 格式化字符串字面值(3.6版本加入)

格式化字符串字面值(简称为 f-字符串)在字符串前加前缀 f 或 F,通过 {expression} 表达式,把 Python 表达式的值添加到字符串内。

  • pi 舍入到小数点后三位
a = f'the value of pi is approximately {math.pi}'
b = f'the value of pi is approximately {math.pi:.3f}'
print(a)  # the value of pi is approximately 3.141592653589793
print(b)  # the value of pi is approximately 3.142
  • ':' 后传递整数,为该字段设置最小字符宽度,常用于列对齐
table = {'jiao': 4172, 'teng': 4098, 'fei': 7678}
for name, phone in table.items():
    print(f'{name}  ==>  {phone}')  # 
for name, phone in table.items():
    print(f'{name:10}  ==>  {phone:10d}')
  • 还有一些修饰符可以在格式化前转换值
animals = 'eels'
number = 10
print(f'My hovercraft is full of {animals}.')
print(f'My hovercraft is full of {number!s}.')  # '!s' 应用 str()
print(f'My hovercraft is full of {animals!r}.')  # '!r' 应用 repr()
print(f'My hovercraft is full of {animals!a}.')  # '!a' 应用 ascii() 
  • 注意:str() 函数返回供人阅读的值,repr() 则生成适于解释器读取的值
```bash
C:\Python38\python.exe C:/Users/X21201/Desktop/python/tiaoce.py
the value of pi is approximately 3.141592653589793
the value of pi is approximately 3.142
jiao  ==>  4172
teng  ==>  4098
fei  ==>  7678
jiao        ==>        4172
teng        ==>        4098
fei         ==>        7678
My hovercraft is full of eels.
My hovercraft is full of 'eels'.
My hovercraft is full of 'eels'.
My hovercraft is full of 10.

1.2 字符串的format方法

# 1、基本用法
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
# 2、花括号中的数字表示传递给 str.format() 方法的对象所在的位置
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
# 3、使用关键字参数名引用值
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
# 4、位置参数和关键字参数可以任意组合
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))

# 与内置函数 vars() 结合使用时,这种方式非常实用,可以返回包含所有局部变量的字典。
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
# 5、如果不想分拆较长的格式字符串,最好按名称引用变量进行格式化,不要按位置。这项操作可以通过传递字典,并用方括号 '[]' 访问键来完成
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table))
# 6、也可以用 '**' 符号,把 table 当作传递的关键字参数
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))

# 7、例如,下面的代码生成一组整齐的列,包含给定整数及其平方与立方:
for x in range(1, 11):
    print('{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * x))

# 其他内容详见 格式化字符串,https://docs.python.org/zh-cn/3/library/string.html#formatstrings
C:\Python38\python.exe C:/Users/X21201/Desktop/python/tiaoce.py
We are the knights who say "Ni!"
spam and eggs
eggs and spam
This spam is absolutely horrible.
The story of Bill, Manfred, and Georg.
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

1.3 手动格式化字符串

# 手动格式化字符串
for x in range(1, 11):
    print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
    # print添加end表示不换行,print打印默认换行
    print(repr(x*x*x).rjust(4))

1.4 旧式字符串格式化方法

% 运算符(求余符)也可用于字符串格式化。给定 'string' % values,则 string 中的 % 实例会以零个或多个 values 元素替换。此操作被称为字符串插值。例如:

>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.

2、读写文件

open() 返回 file object,最常用的参数有两个: open(filename, mode),第一个实参是文件名字符串。第二个实参是包含描述文件使用方式字符的字符串,

  • mode 的值包括 'r' ,表示文件只能读取;
  • 'w' 表示只能写入(现有同名文件会被覆盖);
  • 'a' 表示打开文件并追加内容,任何写入的数据会自动添加到文件末尾。
  • 'r+' 表示打开文件进行读写。
  • mode 实参是可选的,省略时的默认值为 ‘r’
    处理文件对象时,最好使用 with 关键字。优点是,子句体结束后,文件会正确关闭,
>>> with open('workfile') as f:
...     read_data = f.read()

2.1 文件对象的方法

  • f.read(size) 可用于读取文件内容,它会读取一些数据,并返回字符串(文本模式)
  • f.readline() 从文件中读取单行数据;
  • 从文件中读取多行时,可以用循环遍历整个文件对象。这种操作能高效利用内存,快速,且代码简单
>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file
  • list(f)f.readlines(),如需以列表形式读取文件中的所有行
  • f.write(string) 把 string 的内容写入文件,并返回写入的字符数。
  • f.tell() 返回整数,给出文件对象在文件中的当前位置,表示为二进制模式下时从文件开始的字节数,以及文本模式下的意义不明的数字。
  • f.seek(offset, whence) 可以改变文件对象的位置。
>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'

2.2 使用json保存结构化数据

>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'
json.dump(x, f)
x = json.load(f)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿_焦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值