python file operations
python_files_operations
files, file objects
open(name [, mode [, bufsize]]) eg: file = "data.txt" f = open(file, 'r') f = open(file, 'w')
- 'r':read
- 'w':write
- 'a':append
- 'rb':write binary,在unix中文件都可以当作二进制,所以都用'rb'
- 'U' or 'rU': 提供通用支持给换行符,可以写跨平台执行的文件
换行符在windows中为'\r\n', 在unix中为'\n'
methods
- f.read([n]): read at most n bytes
- f.readline([n]): 每行最多读n个
- f.readlines([size])
- f.write(string): 将string写到f中
- f.writelines(lines)
- f.close()
- f.tell(): returns the cur pointer
- f.seek()
文件对象的一些属性:
- f.closed: 如果文件是打开的返回False
- f.mode
- f.name
- f.softspace
- f.newlines
- f.encoding
遍历文件的方式:
# method 1
while True:
line = f.readline()
if not line:
break
# method 2
for line in f:
# process line
sys.stdin, sys.stout, sys.stderr
stdin映射到用户的键盘输入,stdout和stderr输出文本到屏幕 eg:
import sys
sys.stdout.write("enter your name: ")
name = sys.stdin.readline()
上面的等价与raw_input():
name = raw_input("enter your name: ")
raw_input读取的时候不会包括后面的换行符,这点与stdin.readline()不同
print语句中可以用','来表示不用输出换行符:
print 1, 2, 3, 4 #等价与 print 1,2, pirnt 3,4
formatted output
print "The values are %d %7.5f %s" % (x, y, z)
print "The values are {0:d} {1:7.5f} {2}".format(x,y,z)
python3里面,print作为一个函数的形式,如下:
pirnt("the values are", x, y, z, end = '')
如果要重定向输出到文件中,python2中如下:
f = open("output.txt", "w")
print >>f, "hello world"
...
f.close()
在python3里面,可以直接通过print()函数完成:
print("the values are", x,x,z, file = f)
也可以设置元素之间的分隔符:
print("the values are", x, y, z, sep = ',')
'''的使用
'''可以用来做一些格式化的输出,如:
form = """\
Dear %(name)s,
Please send back my %(item)s or pay me $%(amount)0.2f.
Sincerely yours,
Joe Python User
"""
print form % {
'name': 'Mr. Bush',
'item': 'blender',
'amount': 50.00,
}
将会输出
Dear Mr. Bush,
Please send back my blender or pay me $50.00.
Sincerely yours,
Joe Python User
注意第一行'''之后的/表示第一行的那个换行符不要了,否则在前面会多输出一个空行。()里面的关键字将会被替换。
用format()函数也可以达到同样的效果:
form = '''\
Dear {name}s,
Please send back my {item}s or pay me ${amount:0.2f}.
Sincerely yours,
Joe Python User
'''
print form.format(name = "Jack", item = "blender", amount = 50)
还有string里面的Template函数:
import string
form = string.Template("""\
Dear $name,
Please send back my $item or pay me $amount.
Sincerely yours,
Joe Python User
""")
print form.substitute({'name': 'Mr. Bush',
'item': 'blender',
'amount': "%0.2f" % 50.0})
这里用$表示将要被替换的内容

浙公网安备 33010602011771号