GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.runoob.com — Python3 输入和输出 | 菜鸟教程
Python 3 教程
Python3 教程
Python3 简介
Python3 环境搭建
Python3 Pycharm
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 PyQtPython3 输入和输出在前面几个章节中,我们其实已经接触了 Python 的输入输出的功能。本章节我们将具体介绍 Python 的输入输出。 |
| 模式 | 描述 |
|---|---|
| r | 只读方式打开文件(默认模式),文件必须存在,文件指针位于开头。 |
| rb | 以二进制格式只读打开文件(如图片、视频等),文件指针位于开头。 |
| r+ | 以读写方式打开文件,文件必须存在,文件指针位于开头。 |
| rb+ | 以二进制格式读写打开文件,文件指针位于开头。 |
| w | 只写方式打开文件。如果文件存在会被清空;不存在则创建新文件。 |
| wb | 以二进制格式只写打开文件。如果文件存在会被清空;不存在则创建新文件。 |
| w+ | 读写方式打开文件。如果文件存在会被清空;不存在则创建新文件。 |
| wb+ | 以二进制格式读写打开文件。如果文件存在会被清空;不存在则创建新文件。 |
| a | 追加方式打开文件。如果文件存在,写入内容会追加到末尾;不存在则创建新文件。 |
| ab | 以二进制格式追加写入文件,写入内容会追加到末尾;不存在则创建新文件。 |
| a+ | 读写方式打开文件,文件指针默认在末尾(追加模式);不存在则创建新文件。 |
| ab+ | 以二进制格式读写打开文件,文件指针默认在末尾;不存在则创建新文件。 |
说明:在模式后添加 b 表示以二进制方式操作文件,常用于处理图片、音频等非文本文件。
下图很好的总结了这几种模式:
| 模式 | r | r+ | w | w+ | a | a+ |
|---|---|---|---|---|---|---|
| 读 | + | + | + | + | ||
| 写 | + | + | + | + | + | |
| 创建 | + | + | + | + | ||
| 覆盖 | + | + | ||||
| 指针在开始 | + | + | + | + | ||
| 指针在结尾 | + | + |
以下实例将字符串写入到文件 foo.txt 中:
此时打开文件 foo.txt,显示如下:
$ cat /tmp/foo.txt Python 是一个非常好的语言。 是的,的确非常好!!
本节中剩下的例子假设已经创建了一个称为 f 的文件对象。
为了读取一个文件的内容,调用 f.read(size), 这将读取一定数目的数据, 然后作为字符串或字节对象返回。
size 是一个可选的数字类型的参数。 当 size 被忽略了或者为负, 那么该文件的所有内容都将被读取并且返回。
以下实例假定文件 foo.txt 已存在(上面实例中已创建):
执行以上程序,输出结果为:
Python 是一个非常好的语言。 是的,的确非常好!!
f.readline() 会从文件中读取单独的一行。换行符为 '\n'。f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行。
执行以上程序,输出结果为:
Python 是一个非常好的语言。
f.readlines() 将返回该文件中包含的所有行。
如果设置可选参数 sizehint, 则读取指定长度的字节, 并且将这些字节按行分割。
执行以上程序,输出结果为:
['Python 是一个非常好的语言。\n', '是的,的确非常好!!\n']
另一种方式是迭代一个文件对象然后读取每行:
执行以上程序,输出结果为:
Python 是一个非常好的语言。 是的,的确非常好!!
这个方法很简单, 但是并没有提供一个很好的控制。 因为两者的处理机制不同, 最好不要混用。
f.write(string) 将 string 写入到文件中, 然后返回写入的字符数。
执行以上程序,输出结果为:
29
如果要写入一些不是字符串的东西, 那么将需要先进行转换:
执行以上程序,打开 foo1.txt 文件:
$ cat /tmp/foo1.txt
('www.runoob.com', 14)
f.tell() 用于返回文件当前的读/写位置(即文件指针的位置)。文件指针表示从文件开头开始的字节数偏移量。f.tell() 返回一个整数,表示文件指针的当前位置。
如果要改变文件指针当前的位置, 可以使用 f.seek(offset, from_what) 函数。
f.seek(offset, whence) 用于移动文件指针到指定位置。
offset 表示相对于 whence 参数的偏移量,from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾,例如:
from_what 值为默认为0,即文件开头。下面给出一个完整的例子:
在文本文件中 (那些打开文件的模式下没有 b 的), 只会相对于文件起始位置进行定位。
当你处理完一个文件后, 调用 f.close() 来关闭文件并释放系统的资源,如果尝试再调用该文件,则会抛出异常。
当处理一个文件对象时, 使用 with 关键字是非常好的方式。在结束后, 它会帮你正确的关闭文件。 而且写起来也比 try - finally 语句块要简短:
文件对象还有其他方法, 如 isatty() 和 truncate(), 但这些通常比较少用。
python的pickle模块实现了基本的数据序列和反序列化。
通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。
通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
基本接口:
pickle.dump(obj, file, [,protocol])
有了 pickle 这个对象, 就能对 file 以读取的形式打开:
x = pickle.load(file)
注解:从 file 中读取一个字符串,并将它重构为原来的python对象。
file: 类文件对象,有read()和readline()接口。
夏木研
104***[email protected]
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]
伦仔
all***[email protected]
input() 默认输入的为 str 格式,若用数学计算,则需要转换格式,例:
a=input('请输入数字:')
print(a*2)
假设输入数值为3,则上例中得出结果为:
33
若将代码修改为:
a=int(input('请输入数字:'))
print(a*2)
则结果为:
6
伦仔
all***[email protected]
tonysoul
ton***[email protected]
通过 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]
灵魂程序员
102***[email protected]
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]
ZX_茜
360***[email protected]
将 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]
gky9989
guo***[email protected]
对齐方式的取值:
<:左对齐>:右对齐^:居中=:在正负号(如果有的话)和数字之间填充,该对齐选项仅对数字类型有效。它可以输出类似 +0000120 这样的字符串。>>> print("|",format("RUNOOB","*>30"),"|") #左对齐
| ************************RUNOOB |
>>> print("|",format("RUNOOB","*^30"),"|") #居中对齐
| ************RUNOOB************ |
>>> print("|",format("RUNOOB","*<30"),"|") #右对齐
| RUNOOB************************ |
>>> gky9989
guo***[email protected]
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)
结论:
聪聪
fir***[email protected]
对实例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]
取消