<span style="font-size:14px;"># -*- coding: cp936 -*-
#文件读操作 全部读出一次性
file_obj = open('D:\pythonRead.txt','r')
s = file_obj.read()
# print s
file_obj.close()
#文件读操作 指定读取长度
file_obj = open('D:\pythonRead.txt','r')
s = file_obj.read(1024).rstrip()
#print s
file_obj.close()
#文件读操作 一行一行的读
file_obj = open('D:\pythonRead.txt','r')
s = file_obj.readline()
#print s
file_obj.close()
#一次读取所有的行数到list中
file_obj = open('D:\pythonRead.txt','r')
lines = file_obj.readlines()
#print lines
file_obj.close()
#写文件 mode为w表示可读可写 如果文件不存在 会创建一个 写文件会覆盖原来的 追加使用a
file_obj = open('E:\pythonRead.txt','a')
a = 'hello '
b = 'world'
c = '!'
'''
#单行写
file_obj.write(a)
file_obj.write(b)
file_obj.write(c)
'''
#一次性写多行 参数为一个序列
#file_obj.writelines([a,b,c])
#print lines
file_obj.close()
#文件格式化写入
format_obj = open('E:\pythonRead.txt','w')
#长度为10的字符串
head = "%10s%10s%10s\n"%('Id','Name','Record')
format_obj.write(head)
item = "%10s%10s%10s\n"%('10000','Tom','100')
format_obj.write(item)
item1 = "%10s%10s%10s\n"%('10001','Jack','200')
format_obj.write(item1)
format_obj.close()
#while循环读文件
file_while = open('E:\pythonRead.txt','r')
line = file_while.readline()
while line != '':
line = line.rstrip('\n')
print line
line = file_while.readline()
file_obj.close()
#for循环读文件
file_for = open('E:\pythonRead.txt','r')
fileStr = file_for.readlines()
print 'start reading'
for line in fileStr:
line = line.rstrip('\n')
print line
print 'end reading'
file_for.close
#iterator
file_for = open('E:\pythonRead.txt','r')
fileStr = file_for.readlines()
print 'start reading'
#生成一个迭代器
itera = iter(fileStr)
try:
while True:
line = itera.next()
line = line.rstrip('\n')
print line
except StopIteration:
print 'end reading'
file_for.close
</span>