open(name[,mode[,buffering]])
1.如果open函数只带一个文件名参数,那么我们可以获得能读取文件内容的文件对象。open可以以不同mode打开文件:r读 w写 a追加 b二进制 +读写模式 rb读取二进制
2.open的第三个参数buffering:0或者False则IO无缓冲,直接写硬盘;1或者True则IO有缓冲的,大于1表示缓冲区的大小。只有在flush或者close时候才会更新硬盘上的数据。
d:aaa.txt:
i am a beautiful girl,and you?
Software Testing Engineer
exp:
>>> f = open('d:\\aaa.txt','w')
>>> f.write('hello,word')
>>> f.close()
>>> f = open('d:\\aaa.txt','r')
>>> f.read()
'hello,word'
>>> f.read()#这个地方我还不太明白,保留。
''
3.管道:type d:\\aaa.txt | python somescript.py将|前部分的输出 当作后部分的输入。somescript会从他的标准输入sys.stdin中读数据(即type d:\\aaa.txt的标准输出sys.stdout)
somescript.py:
import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print 'Wordcount:',wordcount
执行过程:
C:\Users\Administrator>type d:\\aaa.txt | python d:\\installed\\python2.7.6\\my_py\\test0508.py
Wordcount: 1
4.读写行
f = open('d:\\aaa.txt','r')
>>> f.readline()#读取一行
'1 387581 terry\xca\xb9\xd3\xc3 F220\n'
f.close()
f = open('d:\\aaa.txt','r')
>>> f.readlines()#读取所有,存放在list中
['1 387581 terry\xca\xb9\xd3\xc3 F220\n', '2 341852 lorine\xca\xb9\xd3\xc3 F720\n', '3 901599 xiri\xca\xb9\xd3\xc3 F720\n', '4 827476 xiri\xca\xb9\xd3\xc3 F220\n', '5 545685 \xb2\xe2\xca\xd4\xb1\xb8\xd3\xc3\n']
f.close()
list1 = ['fsd','frewa']
>>> f = open('d:\\aaa.txt','w')
>>> f.writelines(list1)#将list写到文件中
>>> f.close()
>>> f = open('d:\\aaa.txt','r')
>>> f.read()
'fsdfrewa'
每次读写完文件一定记得close!!!!
>>> f = open('d:\\aaa.txt','r')
>>> for i in range(5):
print str(i)+':'+f.readline()
.....
0:s.popen('start cmd /c ')python打开第二个cmd窗口
1:List将序列转为列表 list(‘asfg’) >[‘a’ ‘s ‘’f ‘g’ ]
2:Tuple将序列转为元组
3:Cmp内建函数比较大小
4:Del是一个函数
>>> f.close()
阅读(181) | 评论(0) | 转发(0) |