python open函数 文件操作

open函数 文件操作

 

操作流程:

  1. 打开文件,得到一个文件句柄(对象),赋给一个对象。
  2. 通过文件句柄对文件进行操作。
  3. 关闭文件。
 

使用方法:

open(路径+文件名,读写模式) 
如下:

f = open("test.log","a")
f.write("8")
f.write("9\n")
f.close()

使用追加的方式打开test.log 赋值给f,追加89 然后关闭文件

常用模式有:

r:以读方式打开 
w:以写方式打开 
a:以追加模式打开 
注意:

1、使用'W',文件若存在,首先要清空,然后(重新)创建,

2、使用'a'模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。

 

常用方法有:

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() 返回一行

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

 

posted @ 2017-04-16 23:55  西红柿圆  阅读(3066)  评论(0编辑  收藏  举报