python lession 4 -- IO --

本文深入探讨了Python编程的核心内容,包括字符串操作、表达式转换、文件读写、正则表达式应用、数学库使用、集合操作等,并通过实例展示了如何在实际项目中运用这些知识点。
  • str() repr()
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'

 write a table

>>> for x in range(1,11):
...     print repr(x).rjust(2),
...     print repr(x*x).rjust(3),
...     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

write a table 2.0

 1 >>> for x in range(1,11):
2 ... print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
3 ...
4 1 1 1
5 2 4 8
6 3 9 27
7 4 16 64
8 5 25 125
9 6 36 216
10 7 49 343
11 8 64 512
12 9 81 729
13 10 100 1000

zfill

>>> 'hello'.zfill(10)
'00000hello'
>>> '12.3'.zfill(7)
'00012.3'

str.format()

>>> print "hello {}".format("york")
hello york
>>> print "{1} {0}!".format("york","hello")
hello york!
>>> print "{greeting} {people}".format(greeting="good morning",people="york")
good morning york

'!r'

>>> import math
>>> print 'The value of PI is approximately {}.'.format(math.pi)
The value of PI is approximately 3.14159265359.
>>> print 'The value of PI is approximately {!r}.'.format(math.pi)
The value of PI is approximately 3.141592653589793.
>>> import math
>>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
The value of PI is approximately 3.142.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '{0:10} ==> {1:10d}'.format(name, phone)
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127


Open files

open(filename, mode)
'r' only be read,
'w' only writing,
'a' for appending,
'r+' both reading and writing,
'r' will be assumed if it’s omitted.


file:read() f.read(size), size is optional, return string.caution!: it’s your problem if the file is twice as large as your machine’s memory

>>> f = open("hello.txt")
>>> f.read()
'hello world!\nsecond line!\nthird line!\n'

file:readline() 

>>> f = open("hello.txt")
>>> f.readline()
'hello world!\n'
>>> f.readline()
'second line!\n'
>>> f.readline()
'third line!\n'
>>> f.readline()
''
>>> f.readline()
''

f.readlines()

>>> f.readlines()
['hello world!\n', 'second line!\n', 'third line!\n']

another way to process each line in the file

>>> f = open("hello.txt")
>>> for line in f:
... print line
...
hello world!

second line!

third line!

f.write()

>>> f = open("hello.txt","a")
>>> f.write("this is forth lien\n")

f.tell(), f.seek(position)

>>> f.seek(0)
>>> f.read(1)
'h'
>>> f.tell()
1L

Pickle:read/write some abstract object

pickle.dump(x, f)
x = pickle.load(f)

















转载于:https://www.cnblogs.com/chhyong88/archive/2012/02/06/2340432.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值