Python3 input & output

本文详细介绍了Python中的输入输出(I/O)操作,包括文件读写、格式化输出及数据序列化方法。通过实例展示了如何使用print()、input()、open()等函数进行文件操作,以及利用str.format()、repr()、pickle模块实现数据格式化和持久化存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载: Python3 输入和输出

1. 输出格式美化

  1. 表达式语句
  2. print()
  3. 使用文件对象的write()方法
  4. str.format() 函数来格式化输出值
  5. repr(), str() 将输出转换成字符串
    repr(): 产生一个解释器易读的表达形式
    str(): 返回一个用户易读的表达形式
#repr() 可以转移特殊字符
hello = 'hello,runoob\n'
hellos = repr(hello)

print(hello)
print(hellos)
hello,runoob

'hello,runoob\n'

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

for x in range(1,11):
    print(repr(x).rjust(2), repr(x*x).rjust(3),end=' ')
    print(repr(x*x*x).rjust(4))


for x in range(1,11):
    print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
    # {0:2d}前面为起始的数, 2d表示间距
 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

format()

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

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

常量 PI 的值近似为:3.142。
常量 PI 的值近似为:3.142

2. input()

  1. input()
str = input('please input:')
print('你输入的内容是:',str)
  1. open(file,mode)
  2. write()
# open(filename, mode)
# mode decices how to open the file: read-only,write....
'''
r---read-only
w---write
a---if the file exists, open it; if not, create and write
, the pointer point to the end 
+---用于读写
b--- 以二进制的形式'''
f = open('InputOutput.txt','w')
f.write('Jimmy: Python is an excellent language!\nSyvia: Yes, it is really good!\n')
f.close()

3. 文件对象方法

  1. f.read()
  2. f.readline()
  3. f.readlines():
f = open('InputOutput.txt','r')
str = f.read() #f.read(size)
print(str)
f.close()

Jimmy: Python is an excellent language!
Syvia: Yes, it is really good!
f = open('InputOutput.txt','r')
str = f.readline()
print(str)
f.close()

Jimmy: Python is an excellent language!
f = open('InputOutput.txt','r')
str = f.readlines()  #readlines
print(str)
f.close()

['Jimmy: Python is an excellent language!\n', 'Syvia: Yes, it is really good!\n']
  1. f.tell()返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数。
  2. f.seek(offset, from_what)改变文件当前的位置
    from_what 的值,from_what 值为默认为0,即文件开头,如果是 1 表示当前位置, 2 表示文件的结尾,例如:

seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符

seek(x,1) : 表示从当前位置往后移动x个字符

seek(-x,2):表示从文件的结尾往前移动x个字符

  1. close()
  2. piclkle(): 实现了基本的数据序列和反序列化
    序列化操作将程序中运行的对象信息保存到文件中去,永久存储。

反序列化操作从文件中创建上一次程序保存的对象。

基本接口:
pickle.dump(obj,file,[,protocol])

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(保存字典data1)
pickle.dump(data1,output)

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

f = open('data.pkl','rb')
df = pickle.load(f)
print(df)
f.close()

{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
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()


{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
[1, 2, 3, <Recursion on list with id=2578464597576>]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值