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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM