Python输入输出详解

http://blog.csdn.net/pipisorry/article/details/24143801

Python基本输入输出教程

python内置输入函数

python2输入

raw_input()

python3输入

先在交互式解释器中查看input函数
input(...)  
    input([prompt]) -> string 
    Read a string from standard input.  The trailing newline is stripped.  
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.  On Unix, GNU readline is used if enabled.  The prompt string, if given,  is printed without a trailing newline before reading. 
笔者的Python是3.3的,根据上面的描述可以很清楚的看到,input函数是从标准输入流读取一个字符串,注意换行符是被剥离的。input可以有一个参数prompt,用来提示输入信息的,下面具体name = input("your name is:")  。If the prompt argument is present, it is written to standard output without a trailing newline.  The function then reads a line from input, converts it to a string.

命令行参数读取

$ python test.py arg1 arg2 arg3

Python 中也可以所用 sys 的 sys.argv 来获取命令行参数:

  • sys.argv 是命令行参数列表。

  • len(sys.argv) 是命令行参数个数。

注:sys.argv[0] 表示脚本名。

sys.stdin.readline()

sys.stdin是一个可读的文件对象,sys.stdout是一个可写的文件对象
sys.stdin与可读文件对象具有相同的类型,sys.stdout与可写文件对象具有相同的类型
StringIO:将字符串当做文件来进行处理

sys.stdin.read()和python2 raw_input()的区别联系

    sys.stdin.read()和raw_input()接受和返回的都是原始字符串

sys.stdin.readline() is the fastest one when reading strings and input() when reading integers.lz测试了一下,sys.stdin.readline()无论读取数字还是字符串总是比raw_input()快,不知为何。[sys.stdin.readline() and input(): which one is faster when reading lines of input, and why?]
    区别是raw_input()遇到输入enter停止输入
    sys.stdin.read()读取数据 ctrl+d是结束输入 ,read并不会像input那样遇到回车就返回读取的数据它会缓存或者 等到ctrl d再读取数据
    sys.stdin.readline( )会将标准输入全部获取,包括末尾的'\n',因此用len计算长度时是把换行符'\n'算进去了的,
    但是raw_input( )获取输入时返回的结果是不包含末尾的换行符'\n'的

import sys, os, io

CWD = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(CWD, '..'))
from Oth.Utility.TimeStump import time_block

N = 100000
sys.stdin = io.StringIO(u'''223
334
133
24
34
''' * N)

with time_block('1'):
    while True:
        a = sys.stdin.readline().strip()
        if not a:
            break

# with time_block('2'):
#     for i in range(N * 5):
#         a = raw_input()

python使用字符串构建stdin对象

[操作系统服务:其它模块: io模块]
皮皮Blog

python内置输出函数

1. print()函数

Python2.7中是有print语句和内置print函数的,而在Python3.3中,已经没有print语句了,只有print函数,而其实以前的print语句的功能就是print函数默认形式的功能,所以我们在这里就只看看Python3.3中的内置函数print()。

函数原型print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)  
    Prints the values to a stream, or to sys.stdout by default.  
    Optional keyword arguments:  
    file:  a file-like object (stream); defaults to the current sys.stdout.  
    sep:   string inserted between values, default a space.  
    end:   string appended after the last value, default a newline.  
    flush: whether to forcibly flush the stream.  

从描述中可以看出的是print是支持不定参数的,默认输出到标准输出,而且不清空缓存。各个参数之间默认以空格分隔。输出以一个换行符结束。

flush=False是Python3.3加上去的参数。

objects中每一个对象都会被转化为string的形式,然后写到file指定的文件中,默认是标准输出(sys.stdout),每一个对象之间用sep分隔,默认是空格;所有对象都写到文件后,会写入end,默认是换行。

sep和end参数
d = {1:'a', 2:'b'}
t = (4, 5, 6)
l = ['love', 'happiness']
print(d, t, l, sep='~', end='^_^\n')

{1: 'a', 2: 'b'}~(4, 5, 6)~['love', 'happiness']^_^

d,t,l会被打包成一个tuple,赋给objects。

应用例子

打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”,对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。
for x in range(101):
    print("fizz"[x%3*4::]+"buzz"[x%5*4::] or x)

Note:

1. x不是3位数时,fizz切片操作为空串''

2. print()函数中or前面为''时才会输出后面的,否则只输出前面的字符

输出重定向/错误输出和空输出

默认是输出到sys.stdout

1 python输出到stderr中

py2:    print >> sys.stderr, 'string'

py3:    print('string', file=sys.stderr)

也可以使用sys.stderr.write(msg + "\n")

2 忽略输出:将file参数设置为一个指向空文件的文件对象,如open(os.devnull, 'w'),即可忽略输出。

print('string', file=open(os.devnull, 'w')) 

重定向即时输出到文件:刷新缓冲区flush

示例
a.py: 
print('something')
sleep(30)
命令行中执行python3 a.py > log.txt是不能马上在log.txt中看到print输出的。
需要在a.py的print语句后面加上sys.stdout.flush()
[python 文件输出与重定向 ,输出的内容会在内存中暂存,不会立刻输出到文件中]

标准输入输出stdin/stdout有缓冲区,所以使用print不能立即打印出来
要马上就输出,可以:
1 刷新缓冲区,python中是sys.stdout.flush()
2 python3中支持print支持参数flush,原型:print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
print("hello world!", flush=True)

python输出unicode为中文

python2

print '\u5e94\u8be5'.decode('unicode-escape')

python3

print('\u5e94\u8be5')

结果都是“应该”

print魔法Output caching system

[_] (a single underscore): stores previous output, like Python’sdefault interpreter.

>>> a = 'aaa'
>>> a
'aaa'
>>> print(_)
aaa
在ipython中还另加两个:[__] (two underscores): next previous.[___] (three underscores): next-next previous.

[Output caching system]

2.pretty print - pprint()函数

from pprint import pprint   # pretty-printer
>>> pprint(texts)

Note:

1. pprint 模块( pretty printer )用于打印 Python 数据结构. 当你在命令行下打印特定数据结构时你会发现它很有用(输出格式比较整齐, 便于阅读).e.g.会将输出对象列表中的列表元素自动换行输出。

2. pprint模块不能同时打印两个list( pprint(list1, list2) ),否则会出错。

3. json文档打印

如果你想要漂亮的将文件中的json文档打印出来,你可以用以下这种方式:

cat file.json | python -m json.tools

4.格式化输出

​​​​​
1、输出整数。                          

>>> print("the length of (%s) is %d" %('Python',len('python')),end="!")  
the length of (Python) is 6!  

2、其他进制数。
                                 各个进制数的占位符形式:
                                  %x--- hex 十六进制
                                  %d---dec 十进制
                                  %o---oct   八进制

>>> number=15  
>>> print("dec-十进制=%d\noct-八进制=%o\nhex-十六进制=%x" % (number,number,number))  
dec-十进制=15  
oct-八进制=17  
hex-十六进制=f  

3、输出字符串

>>> print ("%.4s " % ("hello world"))  
hell

>>> print("%5.4s" %("Hello world"))  
 Hell  

这里输出结果为“ Hello”,前面有一个空格
同样对其具体的输出格式也可以写成如下的形式,上面的两个整数可以利用*,来动态代入:

>>> print("%*.*s" %(5,4,"Hello world"))  
 Hell  

这里对Python的print字符串格式输出形式
                                     %A.Bs:A表示输出的总的字符串长度
                                     B表示要输出字符串从开始截取的长度
                                     A<B的时候,输出字符串长度为B(A可以<0 )
                                     A>B的时候前方空格
                                     B>字符串长度时,后面不用空格占位

4、输出浮点数(float)       

>>> print("%10.3f" % 3.141516)  
     3.142  

浮点数的输出控制和字符串相似,不过序注意的是.3表示的输出3位小数,最后一面按四舍五入方式进位。

python列表及字典格式化输出

列表及字典输出时,如果元素中存在转义字符\(如\t),则\输出时会自动重复(\\t)。

还有py2的中文输出问题[python中文字符转义问题]

[numpy输入输出]

新式类格式化format输出和扩展形式

[python字符串、字符串处理函数及字符串相关操作 ]

str()和repr() - 把object转化为str的形式输出

在Python中,字符串(strings)是由内置类str代表的,这是一个类。同时Python还有内置函数str()。

输入输出都是以字符串的形式,print()就是把非str的object转化为其str的形式输出。那么Python怎么把一个object转化为str的形式呢,Python会把这个object传给内置str()函数。

str()回去寻找这个对象的__str__()属性,如果这个对象没有__str__()属性,str()会调用repr()来得到结果。

class wy:  
    def __str__(self):  
        return "abc"  
  
w = wy()  
print(w)

输出:abc

Note:

1. 如果没有定义__str__(),则会调用repr(wy),会输出:

<__main__.wy2 instance at 0x7f900d0c8050>

2. python2中则是__unicode__()函数

from:http://blog.csdn.net/pipisorry/article/details/39231949

ref:Python输入输出(IO)
Python起步之print & input用法总结

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值