open函数 文件操做python
open(路径+文件名,读写模式)
以下:ide
f = open("test.log","a") f.write("8") f.write("9\n") f.close()
使用追加的方式打开test.log 赋值给f,追加89 而后关闭文件函数
经常使用模式有:ui
r:以读方式打开
w:以写方式打开
a:以追加模式打开
注意:spa
一、使用'W',文件若存在,首先要清空,而后(从新)建立,指针
二、使用'a'模式 ,把全部要写入文件的数据都追加到文件的末尾,即便你使用了seek()指向文件的其余地方,若是文件不存在,将自动被建立。code
f.read([size]) size未指定则返回整个文件,若是文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串)对象
>>> f = open('anaconda-ks.cfg','r') >>> print f.read(5) #读取5个字节,不指定则读取全部 #vers >>> f.close <built-in method close of file object at 0x7f96395056f0>
file.readline() 返回一行blog
file.readline([size]) 若是指定了非负数的参数,则表示读取指定大小的字节数,包含“\n”字符。内存
>>> f = open('anaconda-ks.cfg','r') >>> print f.readline() #version=DEVEL >>> print f.readline(1) #返回改行的第一个字节,指定size的大小 #
for line in f: print line #经过迭代器访问
f.write("hello\n") #若是要写入字符串之外的数据,先将他转换为字符串.
f.tell() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).
>>> print f.readline() #version=DEVEL >>> f.tell() 15 >>> f.close
f.seek(偏移量,[起始位置])
用来移动文件指针
偏移量:单位:比特,可正可负
起始位置:0-文件头,默认值;1-当前位置;2-文件尾
cat foo.txt # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line #!/usr/bin/python # Open a file f = open("foo.txt", "r") print "Name of the file: ", f.name line = f.readline() print "Read Line----------------------->: %s" % (line) #读取第一行 print f.tell() #显示游标位置 f.seek(38,1) #偏移38个字符 从当前位置开始 注意这里若是偏移的不是正行是按照当前字节读取到行尾进行计算的 line = f.readline() print "Read Line: %s" % (line) print f.tell() # Close opend file f.close() python seek.py Name of the file: foo.txt Read Line----------------------->: # This is 1st line 19 Read Line: # This is 4th line 76
f.close() 关闭文件
wiht 方法 为了不打开文件后忘记关闭,能够经过with语句来自动管理上下文。
cat seek2.py #!/usr/bin/env python with open('foo.txt','a') as f: f.write('the is new line,hello,world\n') python seek2.py cat foo.txt # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line the is new line,hello,world