python--open用法
open/文件操作
f=open('/tmp/hello','w')
#open(路徑+文件名,讀寫模式)
#讀寫模式:r只讀,r+讀寫,w新建(會(huì)覆蓋原有文件),a追加,b二進(jìn)制文件.常用模式
如:'rb','wb','r+b'等等
讀寫模式的類型有:
rU 或 Ua 以讀方式打開, 同時(shí)提供通用換行符支持 (PEP 278)
w?????以寫方式打開,
a?????以追加模式打開 (從 EOF 開始, 必要時(shí)創(chuàng)建新文件)
r+?????以讀寫模式打開
w+?????以讀寫模式打開 (參見 w )
a+?????以讀寫模式打開 (參見 a )
rb?????以二進(jìn)制讀模式打開
wb?????以二進(jìn)制寫模式打開 (參見 w )
ab?????以二進(jìn)制追加模式打開 (參見 a )
rb+????以二進(jìn)制讀寫模式打開 (參見 r+ )
wb+????以二進(jìn)制讀寫模式打開 (參見 w+ )
ab+????以二進(jìn)制讀寫模式打開 (參見 a+ )
注意:
1、使用'W',文件若存在,首先要清空,然后(重新)創(chuàng)建,
2、使用'a'模式 ,把所有要寫入文件的數(shù)據(jù)都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,將自動(dòng)被創(chuàng)建。
f.read([size]) size未指定則返回整個(gè)文件,如果文件大小>2倍內(nèi)存則有問題.f.read()讀到文件尾時(shí)返回""(空字串)
file.readline() 返回一行
file.readline([size]) 返回包含size行的列表,size 未指定則返回全部行
for line in f: print line #通過迭代器訪問
f.write("hello\n") #如果要寫入字符串以外的數(shù)據(jù),先將他轉(zhuǎn)換為字符串.
f.tell() 返回一個(gè)整數(shù),表示當(dāng)前文件指針的位置(就是到文件頭的比特?cái)?shù)).
f.seek(偏移量,[起始位置])
用來移動(dòng)文件指針
偏移量:單位:比特,可正可負(fù)
起始位置:0-文件頭,默認(rèn)值;1-當(dāng)前位置;2-文件尾
f.close() 關(guān)閉文件
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 |
轉(zhuǎn)載于:https://www.cnblogs.com/kiko0o0/p/8098060.html
總結(jié)
以上是生活随笔為你收集整理的python--open用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 80端口被屏蔽解决方法,80端口穿透之N
- 下一篇: Python基础1 历史 变量