python --- 文件处理,,Welcome to


Welcome to No pain No gain ,we are learning together!!

文件和流

python3中使用 open 打开文件,python2.x是file
open(name[,mode[,buffering]])

mode: ‘r‘ 读模式
‘w‘ 写模式
‘a‘ 追加模式
‘b‘ 二进制模式
‘r+‘ 等同于 ‘r+a‘
‘w+‘ 等同于 ‘w+r‘
‘a+‘ 等同于 ‘a+r‘

buffering 参数是0或者false, 表示无缓冲区,直接对硬盘进行操作
参数是1或者True , 表示使用内存,程序更快
参数大于1,表示缓冲区的大小,(单位是字节)
-1或者负数,表示使用默认缓存区的大小

操作:f = open(‘somefile.txt‘) #默认的打开模式是read

f = open(‘somefile.txt‘ , ‘w‘)
f.write(‘hello , ‘) #会提示写入字符的个数
f.write(‘world‘)
f.close() #如果文件存在,直接覆盖起先的内容,然后写入,如果是写的,则新建


f = open(‘somefiles.txt‘ , ‘r‘) #‘r‘模式是默认的模式,可以不用添加
f.read(4) # 告诉流读取4个字符(字节),会输出前四个字符
f.read() #读取剩余的部分,输出剩余的字符
f.close()



管式输出: $cat somefile.txt | python somescript.py | sort

#somescript.py
import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print ‘Wordcount:‘ . wordcount


前面的例子都是按照流从头往后来处理的。可以用seek 和 tell 来对兴趣的部分进行处理


seek(offset[,whence]):
whence = 0 #表示偏移量是在文件的开始进行
whence = 1 #想当与当前位置,offset可以是负值
whence = 2 #相对于文件结尾的移动


f = open(r‘a.txt‘ , ‘w‘)
f.write(‘0123456789‘)
f.seek(5)
f.write(‘hello world‘)
f = open(r‘a.txt‘)
r.read()
‘01234hello world...‘ #会在第五的位置开始写。


f = open(‘a.txt‘)
f.read(3)
‘012‘
f.read(2)
‘34‘
f.tell()
5l #告诉你在当前第五的位置



f.readline #读取一行
f=open(‘a.txt‘)
for i in range(3):
print str(i) + ‘:‘ + f.readline()

0:......
1:......
2:.....
3:.....


f.readlines #全部读取


f.writeline()
f.writelines()







文件的关闭:
关闭文件,可以避免用完系统中所打开文件的配额
如果想确保文件被关闭了,可以使用try/finally 语句,并在finally中调用close()
方法:
open your file here
try:
write data to your file
finally:
file.close()

实际上有专门对这种情况设计的语句 ,既with语句
with open(‘someone.txt‘) as somefile:
do something(someone.txt)
#把文件负值到 somefile变量上,

如果文件正在内存中,还没有写入文件中,想要在文件中看到内容,需要用 flush 方法

python --- 文件处理

评论关闭