1. 程式人生 > >python open打開文件的方式

python open打開文件的方式

poe automatic 單位 body lin als 通用 將他 hello

open/文件操作
f=open(‘/tmp/hello‘,‘w‘)

#open(路徑+文件名,讀寫模式)

#讀寫模式:r只讀,r+讀寫,w新建(會覆蓋原有文件),a追加,b二進制文件.常用模式

如:‘rb‘,‘wb‘,‘r+b‘等等

讀寫模式的類型有:

rU 或 Ua 以讀方式打開, 同時提供通用換行符支持 (PEP 278)
w 以寫方式打開,
a 以追加模式打開 (從 EOF 開始, 必要時創建新文件)
r+ 以讀寫模式打開
w+ 以讀寫模式打開 (參見 w )
a+ 以讀寫模式打開 (參見 a )
rb 以二進制讀模式打開
wb 以二進制寫模式打開 (參見 w )
ab 以二進制追加模式打開 (參見 a )
rb+ 以二進制讀寫模式打開 (參見 r+ )
wb+ 以二進制讀寫模式打開 (參見 w+ )
ab+ 以二進制讀寫模式打開 (參見 a+ )


註意:

1、使用‘W‘,文件若存在,首先要清空,然後(重新)創建,

2、使用‘a‘模式 ,把所有要寫入文件的數據都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,將自動被創建。



f.read([size]) size未指定則返回整個文件,如果文件大小>2倍內存則有問題.f.read()讀到文件尾時返回""(空字串)

file.readline() 返回一行

file.readline([size]) 返回包含size行的列表,size 未指定則返回全部行

for line in f: print line #通過叠代器訪問

f.write("hello\n") #如果要寫入字符串以外的數據,先將他轉換為字符串.

f.tell() 返回一個整數,表示當前文件指針的位置(就是到文件頭的比特數).

f.seek(偏移量,[起始位置])

用來移動文件指針

偏移量:單位:比特,可正可負

起始位置:0-文件頭,默認值;1-當前位置;2-文件尾

f.close() 關閉文件

Code:


#!/usr/bin/env python
# Filename: using_file.py

poem=‘‘‘\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!‘‘‘
f=file(‘poem.txt‘,‘w‘) # open for ‘w‘riting
f.write(poem) # write text to file
f.close() # close the file
f=file(‘poem.txt‘)

# if no mode is specified, ‘r‘ead mode is assumed by default
while True:
line=f.readline()
if len(line)==0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close()
# close the file

python open打開文件的方式