python 文件處理

複製到有道雲打開會產生目錄vim

打開文件

python進行文件讀寫的函數open或file函數

使用open打開文件:

默認使用平臺編碼
>>> fo = open('/tmp/make/ab.txt',encoding='utf-8') #打開文件
>>> fo.read() #使用read讀取數據
>>> fo.close() #關閉

file打開文件(限python2中)

>>> f1 = file('/tmp/make/ab.txt')
>>> f1.read()
>>> f1.close()
>>> f1.read() #關閉以後再讀取時讀取不到的

上下文管理

with open('a.text','r',encoding='utf-8') as f,open('b.text','r',encoding='utf-8') as b_f:
    print(f.read())
    print(b_f.read())

文件操做

r只讀:

f = open('test.log','r',encoding='utf-8')
a = f.read()
print(a)

w 寫(有文件則先清空再寫,沒有則建立再寫)

寫入,先刪除原文件,在從新寫入,若是我那件沒有則建立
f = open('test.log','w',encoding='utf-8')
a = f.write('car.\n索寧')
print(a)    #返回字符

a 追加(指針會先移動到最後)

f = open('test.log','a',encoding='utf-8')
a = f.write('girl\n索寧')
print(a)    #返回字符

讀寫 r+

f = open('test.log','r+',encoding='utf-8')
a = f.read()
print(a)
f.write('nick')

寫讀 w+(會先清空!!!)

寫讀,先刪除原文件,在從新寫入,若是文件沒有則建立(能夠寫入輸出)
f = open('test.log','w+',encoding='utf-8')
a = f.read()
print(a)
f.write('jenny')

寫讀 a+(指針先移到最後)

f = open('test.log','a+',encoding='utf-8')
f.seek(0)   #指針位置調爲0
a = f.read()
print(a)
b = f.write('nick')
print(b)

rb

f = open('test.log','rb')
a = f.read()
print(str(a,decode='utf-8')) #須要解碼

f=open('sb.jpg','r',encoding='utf-8') #文本的方式讀不了二進制文件
print(f.read())

with open('sb.jpg','rb') as read_f,\
        open('sb_alex.jpg','wb') as write_f:
    data=read_f.read()
     write_f.write(data)

ab

f = open('test.log','ab')
f.write(bytes('索寧\ncar',encoding='utf-8'))
f.write(b'jenny')

關閉文件

f.close()

內存刷到硬盤

f.flush()

獲取指針位置

f.tell()

指定文件中指針位置

f.seek(0)

讀取所有內容(若是設置了size,就讀取size字節)

f.read()
f.read(9)

讀取一行

f.readline()

讀到的每一行內容做爲列表的一個元素

f.readlines()

U :支持全部換行符號。「」,"\n"."\r\n"優化

文件對象方法:

一、-FileObject.close()

二、readline

格式:String=FileObject.readline([size])
說明:每次讀取文件的一行
size:是指每行每次讀取size個字節,知道行的末尾
例:
>>> f1 = open('test.txt') #打開文件
>>> f1.readline() #每次讀取一行
'hello\n'
>>> f1.readline()
"what's\n"
>>> f1.readline()
'your\n'
>>> f1.readline()
'name\n'
>>> f1.readline() #超出以後readline會讀取空字符串
>>>..
>>> f1,close()

三、readlines

格式:List=FileObject.readlines([size])
說明:多行讀,返回一個列表 (讀取全部而後以列表的形式保存下來)
size:每行讀入size字符,而後繼續按size讀,而不是每次讀入行的四則個字符
例:
>>> f1=open('test.txt')
>>> f1.readlines()
['hello\n', "what's\n", 'your\n', 'name\n']

四、read

with open('a.txt','r',encoding='utf-8') as f:
    print(f.read(4)) #數字指的是讀的是字符

with open('a.txt','rb') as f:
    print(f.read(1)) #數字指的是讀的是字符

五、next

格式:-FileObject.next()
例:
>>> f1 = open('test.txt')
>>> f1.next()
'hello\n'
>>> f1.next()
"what's\n"
>>> f1.next()
'your\n'
>>> f1.next()
'name\n'
>>> f1.next() #跟readline不一樣的是next超出以後會中止迭代,給出警示
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

六、write

格式:FileObject.write(string)
說明:write和後面的weitelines在寫入前會是否清楚文件中原來的s數據,
再從新寫入新的內容,取決於打開文件的模式。

七、writelines

格式:FileObject.writelines(list)
說明:多行寫
效率比write高,速度更快,少許寫入可使用write

八、FileObjectseek (偏移量,選項)

選項=0時,表示將文件指針指向從文件頭部到「偏移量」字節處。
選項=1時,表示文件指針指向從文件的當前位置,向後移動「偏移量」字節
選項=2時,表示將文件指針指向從文件的尾部向前移動「偏移量」字節。

九、-FileObject.flush

提交更新
例:
>>> f1 = open('test.txt','a')
>>> l = ['one\n','two\n','three\n']
>>> f1.writelines(l)
>>> f1.flush() #flush實現文件數據的提交
>>> f1.close()

十、find查找

>>> msg = "what's your company's name?"
>>> msg
"what's your company's name?"
>>> msg.find('name')
22
>>> msg.find('company')
12

十一、seek(指定光標位置)

with open('a.txt','r',encoding='utf-8') as f:
    f.seek(3) #seek內指定的數字表明字節(指定光標位置)
    print(f.tell()) #當前光標所在的位置
    print(f.read())
    
with open('b.txt','rb') as f:
    f.read()
    f.seek(3) #默認狀況,是以文件起始位置做爲開始,日後移動3個bytes
    f.read(1)
    print(f.tell())
    f.seek(2,1) #1 表明以當前光標所在的位置爲開始,日後移動2個 bytes
    print(f.tell())

    f.seek(-1,2) #2表以當前光標所在的位置爲開始,日後移動2個 bytes
    print(f.tell())

    f.seek(0,2)

十二、truncate截斷

with open('a.txt','r+',encoding='utf-8') as f:
    #f.seek(3) #seek內指定的數字表明字節
    print(f.read())

    f.truncate(3)

Python的文件類型

一、源代碼

Python源代碼的文件已「py」爲擴展名,由Python程序解釋,不須要編譯;

用./1.py時 須要寫Python的路徑#!/usr/bin/python,而後chmod賦予權限

二、字節代碼

Python源文件經編譯後生成的擴展名爲「pyc」的文件;
編譯方法 import py_compile
py_compile.compile("hello.py") #hello py爲上分文件
例:vim 1.py
#!/usr/bin/python
print 'hello'
$chmod +x 1.py
$vim 2.py
import py_compile
py_compile.compile("1.py")
$python 2.py
$ls
1.py 1.pyc 2.py

三、優化代碼

通過優化的原文件,擴展名爲「.pyo」
python -O -m py_commpile hello.py
例:$python -O -m py_commpile 1.py
$ls
1.py 1.pyc 1.pyo
$chmod +x *
python 1.py python 1.pyc python 1.pyo #這三種的執行結果同樣,但python1.py最經常使用
能夠簡明的瞭解那裏有錯誤

tail -f access.log

import time
with open('access.log','r',encoding='utf-8') as f:
    f.seek(0,2)
    while True:
        line=f.readline().strip()
        if line:
            print('新增一行日誌',line)
        time.sleep(0.5)

文件複製、修改

複製:

打開一個a文件,用readline讀取到b文件
with open('a.txt','r') as a_f,open('b.txt','w') as b_f:
    for line in a_f.readlines():
        b_f.write(line)

修改:

import os
with open('a.txt','r') as a_f,open('b.txt','w') as b_f:
    for line in a_f.readlines():
        if line.startswith('111'):
            line='222333\n'
    b_f.write(line)

os.remove('a.txt')
os.rename('b.txt','a.txt')  #更名
相關文章
相關標籤/搜索