菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python3 输入和输出

在前面几个章节中,我们其实已经接触了 Python 的输入输出的功能。本章节我们将具体介绍 Python 的输入输出。


输出格式美化

Python两种输出值的方式: 表达式语句和 print() 函数。

第三种方式是使用文件对象的 write() 方法,标准输出文件可以用 sys.stdout 引用。

如果你希望输出的形式更加多样,可以使用 str.format() 函数来格式化输出值。

如果你希望将输出的值转成字符串,可以使用 repr() 或 str() 函数来实现。

  • str(): 函数返回一个用户易读的表达形式。
  • repr(): 产生一个解释器易读的表达形式。

例如

>>> s = 'Hello, Runoob'
>>> str(s)
'Hello, Runoob'
>>> repr(s)
"'Hello, Runoob'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x 的值为: ' + repr(x) + ', y 的值为:' + repr(y) + '...'
>>> print(s)
x 的值为: 32.5, y 的值为:40000...
>>> # repr() 函数可以转义字符串中的特殊字符
... hello = 'hello, runoob\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, runoob\n'
>>> # repr() 的参数可以是 Python 的任何对象
... repr((x, y, ('Google', 'Runoob')))
"(32.5, 40000, ('Google', 'Runoob'))"

这里有两种方式输出一个平方与立方的表:

>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # 注意前一行 'end' 的使用
... print(repr(x*x*x).rjust(4))
...
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

>>> for x in range(1, 11):
... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
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

注意:在第一个例子中, 每列间的空格由 print() 添加。

这个例子展示了字符串对象的 rjust() 方法, 它可以将字符串靠右, 并在左边填充空格。

还有类似的方法, 如 ljust() 和 center()。 这些方法并不会写任何东西, 它们仅仅返回新的字符串。

另一个方法 zfill(), 它会在数字的左边填充 0,如下所示:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

str.format() 的基本使用如下:

>>> print('{}网址: "{}!"'.format('菜鸟教程', 'www.runoob.com'))
菜鸟教程网址: "www.runoob.com!"

括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。

在括号中的数字用于指向传入对象在 format() 中的位置,如下所示:

>>> print('{0} 和 {1}'.format('Google', 'Runoob'))
Google 和 Runoob
>>> print('{1} 和 {0}'.format('Google', 'Runoob'))
Runoob 和 Google

如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数。

>>> print('{name}网址: {site}'.format(name='菜鸟教程', site='www.runoob.com'))
菜鸟教程网址: www.runoob.com

位置及关键字参数可以任意的结合:

>>> print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'Runoob', other='Taobao'))
站点列表 Google, Runoob, 和 Taobao。

!a (使用 ascii()), !s (使用 str()) 和 !r (使用 repr()) 可以用于在格式化某个值之前对其进行转化:

>>> import math
>>> print('常量 PI 的值近似为: {}。'.format(math.pi))
常量 PI 的值近似为: 3.141592653589793
>>> print('常量 PI 的值近似为: {!r}。'.format(math.pi))
常量 PI 的值近似为: 3.141592653589793

可选项 : 和格式标识符可以跟着字段名。 这就允许对值进行更好的格式化。 下面的例子将 Pi 保留到小数点后三位:

>>> import math
>>> print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi))
常量 PI 的值近似为 3.142

: 后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用。

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> for name, number in table.items():
... print('{0:10} ==> {1:10d}'.format(name, number))
...
Google ==> 1
Runoob ==> 2
Taobao ==> 3

如果你有一个很长的格式化字符串, 而你不想将它们分开, 那么在格式化时通过变量名而非位置会是很好的事情。

最简单的就是传入一个字典, 然后使用方括号 [] 来访问键值 :

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
Runoob: 2; Google: 1; Taobao: 3

也可以通过在 table 变量前使用 ** 来实现相同的功能:

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
Runoob: 2; Google: 1; Taobao: 3

旧式字符串格式化

% 操作符也可以实现字符串格式化。 它将左边的参数作为类似 sprintf() 式的格式化字符串, 而将右边的代入, 然后返回格式化后的字符串. 例如:

>>> import math
>>> print('常量 PI 的值近似为:%5.3f。' % math.pi)
常量 PI 的值近似为:3.142

因为 str.format() 是比较新的函数, 大多数的 Python 代码仍然使用 % 操作符。但是因为这种旧式的格式化最终会从该语言中移除, 应该更多的使用 str.format().


读取键盘输入

Python 提供了 input() 内置函数从标准输入读入一行文本,默认的标准输入是键盘。

实例

#!/usr/bin/python3

str = input("请输入:");
print ("你输入的内容是: ", str)

这会产生如下的对应着输入的结果:

请输入:菜鸟教程
你输入的内容是: 菜鸟教程

读和写文件

在 Python 中,文件操作通过 open() 函数完成。该函数会返回一个文件对象(file object),用于后续的读取或写入操作。

open() 的基本语法如下:

open(filename, mode)
  • filename:要访问的文件路径(字符串)。
  • mode:文件打开模式,用于指定读写方式(如只读、写入、追加等)。该参数是可选的,默认值为 r(只读)。

常见文件打开模式如下(建议重点掌握 r / w / a):

模式 描述
r 只读方式打开文件(默认模式),文件必须存在,文件指针位于开头。
rb 以二进制格式只读打开文件(如图片、视频等),文件指针位于开头。
r+ 以读写方式打开文件,文件必须存在,文件指针位于开头。
rb+ 以二进制格式读写打开文件,文件指针位于开头。
w 只写方式打开文件。如果文件存在会被清空;不存在则创建新文件。
wb 以二进制格式只写打开文件。如果文件存在会被清空;不存在则创建新文件。
w+ 读写方式打开文件。如果文件存在会被清空;不存在则创建新文件。
wb+ 以二进制格式读写打开文件。如果文件存在会被清空;不存在则创建新文件。
a 追加方式打开文件。如果文件存在,写入内容会追加到末尾;不存在则创建新文件。
ab 以二进制格式追加写入文件,写入内容会追加到末尾;不存在则创建新文件。
a+ 读写方式打开文件,文件指针默认在末尾(追加模式);不存在则创建新文件。
ab+ 以二进制格式读写打开文件,文件指针默认在末尾;不存在则创建新文件。

说明:在模式后添加 b 表示以二进制方式操作文件,常用于处理图片、音频等非文本文件。

下图很好的总结了这几种模式:

模式 r r+ w w+ a a+
+ + + +
+ + + + +
创建 + + + +
覆盖 + +
指针在开始 + + + +
指针在结尾 + +

以下实例将字符串写入到文件 foo.txt 中:

实例

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "w")

f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )

# 关闭打开的文件
f.close()
  • 第一个参数为要打开的文件名。
  • 第二个参数描述文件如何使用的字符。 mode 可以是 'r' 如果文件只读, 'w' 只用于写 (如果存在同名文件则将被删除), 和 'a' 用于追加文件内容; 所写的任何数据都会被自动增加到末尾. 'r+' 同时用于读写。 mode 参数是可选的; 'r' 将是默认值。

此时打开文件 foo.txt,显示如下:

$ cat /tmp/foo.txt 
Python 是一个非常好的语言。
是的,的确非常好!!

文件对象的方法

本节中剩下的例子假设已经创建了一个称为 f 的文件对象。

f.read()

为了读取一个文件的内容,调用 f.read(size), 这将读取一定数目的数据, 然后作为字符串或字节对象返回。

size 是一个可选的数字类型的参数。 当 size 被忽略了或者为负, 那么该文件的所有内容都将被读取并且返回。

以下实例假定文件 foo.txt 已存在(上面实例中已创建):

实例

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

str = f.read()
print(str)

# 关闭打开的文件
f.close()

执行以上程序,输出结果为:

Python 是一个非常好的语言。
是的,的确非常好!!

f.readline()

f.readline() 会从文件中读取单独的一行。换行符为 '\n'。f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行。

实例

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

str = f.readline()
print(str)

# 关闭打开的文件
f.close()

执行以上程序,输出结果为:

Python 是一个非常好的语言。

f.readlines()

f.readlines() 将返回该文件中包含的所有行。

如果设置可选参数 sizehint, 则读取指定长度的字节, 并且将这些字节按行分割。

实例

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

str = f.readlines()
print(str)

# 关闭打开的文件
f.close()

执行以上程序,输出结果为:

['Python 是一个非常好的语言。\n', '是的,的确非常好!!\n']

另一种方式是迭代一个文件对象然后读取每行:

实例

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "r")

for line in f:
print(line, end='')

# 关闭打开的文件
f.close()

执行以上程序,输出结果为:

Python 是一个非常好的语言。
是的,的确非常好!!

这个方法很简单, 但是并没有提供一个很好的控制。 因为两者的处理机制不同, 最好不要混用。

f.write()

f.write(string) 将 string 写入到文件中, 然后返回写入的字符数。

实例

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo.txt", "w")

num = f.write( "Python 是一个非常好的语言。\n是的,的确非常好!!\n" )
print(num)
# 关闭打开的文件
f.close()

执行以上程序,输出结果为:

29

如果要写入一些不是字符串的东西, 那么将需要先进行转换:

实例

#!/usr/bin/python3

# 打开一个文件
f = open("/tmp/foo1.txt", "w")

value = ('www.runoob.com', 14)
s = str(value)
f.write(s)

# 关闭打开的文件
f.close()

执行以上程序,打开 foo1.txt 文件:

$ cat /tmp/foo1.txt 
('www.runoob.com', 14)

f.tell()

f.tell() 用于返回文件当前的读/写位置(即文件指针的位置)。文件指针表示从文件开头开始的字节数偏移量。f.tell() 返回一个整数,表示文件指针的当前位置。

f.seek()

如果要改变文件指针当前的位置, 可以使用 f.seek(offset, from_what) 函数。

f.seek(offset, whence) 用于移动文件指针到指定位置。

offset 表示相对于 whence 参数的偏移量,from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾,例如:

  • seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符
  • seek(x,1) : 表示从当前位置往后移动x个字符
  • seek(-x,2):表示从文件的结尾往前移动x个字符

from_what 值为默认为0,即文件开头。下面给出一个完整的例子:

>>> f = open('/tmp/foo.txt', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5) # 移动到文件的第六个字节
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # 移动到文件的倒数第三字节
13
>>> f.read(1)
b'd'

f.close()

在文本文件中 (那些打开文件的模式下没有 b 的), 只会相对于文件起始位置进行定位。

当你处理完一个文件后, 调用 f.close() 来关闭文件并释放系统的资源,如果尝试再调用该文件,则会抛出异常。

>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

当处理一个文件对象时, 使用 with 关键字是非常好的方式。在结束后, 它会帮你正确的关闭文件。 而且写起来也比 try - finally 语句块要简短:

>>> with open('/tmp/foo.txt', 'r') as f:
... read_data = f.read()
>>> f.closed
True

文件对象还有其他方法, 如 isatty() 和 trucate(), 但这些通常比较少用。


pickle 模块

python的pickle模块实现了基本的数据序列和反序列化。

通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。

通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。

基本接口:

pickle.dump(obj, file, [,protocol])

有了 pickle 这个对象, 就能对 file 以读取的形式打开:

x = pickle.load(file)

注解:从 file 中读取一个字符串,并将它重构为原来的python对象。

file: 类文件对象,有read()和readline()接口。

实例 1

#!/usr/bin/python3
import pickle

# 使用pickle模块将数据对象保存到文件
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

实例 2

#!/usr/bin/python3
import pprint, pickle

#使用pickle模块从文件中重构python对象
pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()
AI 思考中...

8 篇笔记 写笔记

  1. #0

    夏木研

    104***[email protected]

    111

    python文件写入也可以进行网站爬虫,我的python版本是3.6,以下代码是打开project.txt文件,并向里面写入http://www.baidu.com网站代码。

    from urllib import request
    response = request.urlopen("http://www.baidu.com/") # 打开网站
    fi = open("project.txt", 'w') # open一个txt文件
    page = fi.write(str(response.read())) # 网站代码写入
    fi.close() # 关闭txt文件
    

    夏木研

    104***[email protected]

    9年前 (2017年06月14日)
  2. #0

    伦仔

    all***[email protected]

    268

    input() 默认输入的为 str 格式,若用数学计算,则需要转换格式,例:

    a=input('请输入数字:')
    print(a*2)

    假设输入数值为3,则上例中得出结果为:

    33

    若将代码修改为:

    a=int(input('请输入数字:'))
    print(a*2)

    则结果为:

    6

    伦仔

    all***[email protected]

    9年前 (2017年08月10日)
  3. #0

    tonysoul

    ton***[email protected]

    184

    通过 pickle 序列化实现一个简单联系人信息管理:

    import pickle
    import os
    datafile = 'person.data'
    line = '======================================='
    message = '''
    =======================================
    Welcome bookmark:
     press 1 to show list
     press 2 to add pepole
     press 3 to edit pepole
     press 4 to delete pepole
     press 5 to search pepole
     press 6 to show menu
     press 0 to quit
    =======================================
    '''
    print(message)
    class Person(object):
     """通讯录联系人"""
     def __init__(self, name, number):
     self.name = name
     self.number = number
    # 获取数据
    def get_data(filename=datafile):
     # 文件存在且不为空
     if os.path.exists(filename) and os.path.getsize(filename):
     with open(filename,'rb') as f:
     return pickle.load(f)
     return None
     
    # 写入数据
    def set_data(name, number, filename=datafile):
     personList = {} if get_data() == None else get_data()
     with open(filename,'wb') as f:
     personList[name] = Person(name,number)
     pickle.dump(personList,f)
    # 保存字典格式的数据到文件
    def save_data(dictPerson, filename=datafile):
     with open(filename,'wb') as f:
     pickle.dump(dictPerson,f)
    # 显示所有联系人
    def show_all():
     personList = get_data()
     if personList:
     for v in personList.values():
     print(v.name,v.number)
     print(line)
     else:
     print('not yet person,please add person')
     print(line)
    # 添加联系人
    def add_person(name,number):
     set_data(name,number)
     print('success add person')
     print(line)
    # 编辑联系人
    def edit_person(name,number):
     personList = get_data()
     if personList:
     personList[name] = Person(name,number)
     save_data(personList)
     print('success edit person')
     print(line)
    # 删除联系人
    def delete_person(name):
     personList = get_data()
     if personList:
     if name in personList:
     del personList[name]
     save_data(personList)
     print('success delete person')
     else:
     print(name,' is not exists in dict')
     print(line)
    # 搜索联系人
    def search_person(name):
     personList = get_data()
     if personList:
     if name in personList.keys():
     print(personList.get(name).name, personList.get(name).number)
     else:
     print('No this person of ',name)
     print(line)
     
    while True:
     num = input('>>')
     if num == '1':
     print('show all personList:')
     show_all()
     elif num == '2':
     print('add person:') 
     name = input('input name>>')
     number = input('input number>>')
     add_person(name,number)
     elif num == '3':
     print('edit person:')
     name = input('input name>>')
     number = input('input number>>')
     edit_person(name,number)
     elif num == '4':
     print('delete person:')
     name = input('input name>>')
     delete_person(name)
     elif num == '5':
     print('search :')
     name = input('input name>>')
     search_person(name)
     elif num == '6':
     print(message)
     elif num == '0':
     break
     else:
     print('input error, please retry')

    tonysoul

    ton***[email protected]

    8年前 (2018年03月10日)
  4. #0

    灵魂程序员

    102***[email protected]

    79

    格式化输出

    1、整数的输出

    语法说明

    格式化符号格式说明备注 %o 八进制 oct%d 十进制 dec%x 十六进制 hex。

    举个栗子

    print('%o' % 20) # 八进制24
    print('%d' % 20) # 十进制20
    print('%x' % 24) # 十六进制18

    2、浮点数输出

    语法说明

    格式化符号说明备注 %f 保留小数点后面六位有效数字 float%e 保留小数点后面六位有效数字 %g 在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法。

    举个栗子:

    print('%f' % 1.11) # 默认保留6位小数1.110000
    print('%.1f' % 1.11) # 取1位小数1.1
    print('%e' % 1.11) # 默认6位小数,用科学计数法1.110000e+00
    print('%.3e' % 1.11) # 取3位小数,用科学计数法1.110e+00
    print('%g' % 1111.1111) # 默认6位有效数字1111.11
    print('%.7g' % 1111.1111) # 取7位有效数字1111.111
    print('%.2g' % 1111.1111) # 取2位有效数字,自动转换为科学计数法1.1e+03

    3、字符串输出

    语法说明

    格式化符号说明备注 %s 字符串输出 string%10s 右对齐,占位符 10位%-10s 左对齐,占位符 10 位 %.2s 截取 2 位字符串 %10.2s10 位占位符,截取两位字符串。

    举个栗子:

    print('%s' % 'hello world') # 字符串输出hello world
    print('%20s' % 'hello world') # 右对齐,取20位,不够则补位 hello world
    print('%-20s' % 'hello world') # 左对齐,取20位,不够则补位hello world 
    print('%.2s' % 'hello world') # 取2位he
    print('%10.2s' % 'hello world') # 右对齐,取2位 he
    print('%-10.2s' % 'hello world') # 左对齐,取2位he

    灵魂程序员

    102***[email protected]

    8年前 (2018年03月20日)
  5. #0

    ZX_茜

    360***[email protected]

    68

    将 mode 设置为 w+ 或 a+ 时,发现直接进行读操作,得到的内容都是空,但原因不太相同:

    如果 mode 设置为 w+,即使没有执行 write 操作,也会将文件内容清空,因此这个时候直接进行读草稿,读到的是空内容。

    f = open("E:\\administrator\\Desktop\\test.txt", "w+")

    如果 mode 设置为 a+,文件指针位置默认在最后面,因为读内容时,是按照指针的位置往后读,所以如果指针位置在最后,那读出来的是空,在读之前,一定要注意确认好指针位置是对的。

    f = open("E:\\administrator\\Desktop\\test.txt", "a+")
    f.write("append content")
    print(f.tell()) #此时指针在文件字符末尾处
    f.seek(0)
    print(f.tell()) # 指针回到0的位置
    str = f.read()
    print(str)
    f.close()f = open("E:\\administrator\\Desktop\\test.txt", "w+")

    ZX_茜

    360***[email protected]

    8年前 (2018年08月08日)
  6. #0

    gky9989

    guo***[email protected]

    42

    对齐方式的取值:

    • <:左对齐
    • >:右对齐
    • ^:居中
    • =:在正负号(如果有的话)和数字之间填充,该对齐选项仅对数字类型有效。它可以输出类似 +0000120 这样的字符串。
    >>> print("|",format("RUNOOB","*>30"),"|") #左对齐
    | ************************RUNOOB |
    >>> print("|",format("RUNOOB","*^30"),"|") #居中对齐
    | ************RUNOOB************ |
    >>> print("|",format("RUNOOB","*<30"),"|") #右对齐
    | RUNOOB************************ |
    >>> 

    gky9989

    guo***[email protected]

    7年前 (2020年02月01日)
  7. #0

    关于 str() 和 repr() 的区别

    str()和repr()输出的都是 str 类型

    >>> a = 10
    >>> type(str(a))
    <class 'str'>
    >>> type(repr(a))
    <class 'str'>

    但是 str() 更注重可读性,repr() 更注重数据本身的信息:

    >>> from datetime import datetime
    >>> now = datetime.now()
    >>> print(str(now))
    2017年04月22日 15:41:33.012917
    >>> print(repr(now))
    datetime.datetime(2017, 4, 22, 15, 41, 33, 12917)

    结论:

    • str() 的输出追求可读性,输出格式要便于理解,适合用于输出内容到用户终端。
    • repr() 的输出追求明确性,除了对象内容,还需要展示出对象的数据类型信息,适合开发和调试阶段使用。
    Even 5年前 (2021年05月27日)
  8. #0

    聪聪

    fir***[email protected]

    13

    对实例1做了下修改:

    1.将文件改为追加写入的方式

    2.末尾增加了基于while循环的load,把写入的打印出来查看,用循环是因为发现pickle.load(f)每次运行只能读取一行

    import pickle
    # 使用pickle模块将数据对象保存到文件
    data1 = {'a': [1, 2.0, 3, 4+6j],
     'b': ('string', u'Unicode string'),
     'c': None}
    selfref_list = [1, 2, 3]
    selfref_list.append(selfref_list)
    output = open('data2.pkl', 'ab') #修改为追加写入
    # Pickle dictionary using protocol 0.
    pickle.dump(data1, output)
    # Pickle the list using the highest protocol available.
    pickle.dump(selfref_list, output, -1)
    output.close()
    #循环读取直至最后一行
    with open('data2.pkl','rb')as f:
     while True:
     try:
     print(pickle.load(f))
     except EOFError:
     f.close()
     break

    聪聪

    fir***[email protected]

    5年前 (2021年09月01日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /