标签:io ar os 使用 for sp 文件 on bs
python_files_operations
open(name [, mode [, bufsize]]) eg: file = "data.txt" f = open(file, ‘r‘) f = open(file, ‘w‘)
换行符在windows中为‘\r\n‘, 在unix中为‘\n‘
文件对象的一些属性:
遍历文件的方式:
# method 1
while True:
line = f.readline()
if not line:
break
# method 2
for line in f:
# process line
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
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})
这里用$表示将要被替换的内容
标签:io ar os 使用 for sp 文件 on bs
原文地址:http://www.cnblogs.com/jolin123/p/4077598.html