1. 程式人生 > >python學習筆記文件操作(六)

python學習筆記文件操作(六)

python

1、文件操作流程:

  1. 打開文件,得到文件句柄並賦值給一個變量

  2. 通過句柄對文件進行操作

  3. 關閉文件

如下文件:

2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}
2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap
2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator
2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state ‘stopping‘
2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}
2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN

操作流程:

f = open(‘log.txt‘,‘r‘)
print(f.read())
f.close()

註意: 在win系統中log文件是utf8保存的,打開文件時open函數是通過操作系統打開的文件,而win操作系統默認的是gbk編碼,所以直接打開會亂碼,需要f=open(‘hello‘,encoding=‘utf8‘),hello文件如果是gbk保存的,則直接打開即可。


2、文件打開模式

# ========= ===============================================================
#
#     Character Meaning
#
#     --------- ---------------------------------------------------------------
#
#     ‘r‘       open for reading (default)
#
#     ‘w‘       open for writing, truncating the file first
#
#     ‘x‘       create a new file and open it for writing
#
#     ‘a‘       open for writing, appending to the end of the file if it exists
#
#     ‘b‘       binary mode
#
#     ‘t‘       text mode (default)
#
#     ‘+‘       open a disk file for updating (reading and writing)
#
#     ‘U‘       universal newline mode (deprecated)
#
# ========= ===============================================================


3、文件操作方法


獲取文件內容

f = open(‘log.txt‘,‘r‘) 
data = f.read() 
print(data)
f.close()

輸出:

2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}

2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap

2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator

2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state ‘stopping‘

2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}

2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN

===========================================================================================

f = open(‘log.txt‘,‘r‘)
data1 = f.read(10) #讀取10個字符。(在這裏漢字也只占一個單位)
print(data1)
f.close()

輸出:

2017-03-24



readline和readlines

===========================================================================================

f = open(‘log.txt‘,‘r‘)
print(f.readlines()) #返回的是一個列表,註意換行符
f.close()

輸出:

[‘2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}\n‘, ‘2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap\n‘, ‘2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator\n‘, "2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state ‘stopping‘\n", ‘2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}\n‘, ‘2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN‘]

===========================================================================================

f = open(‘log.txt‘,‘r‘)
print(f.readline()) #逐行讀取
print(f.readline())
print(f.readline(),f.readline(),f.readline()) #逐行讀取,每行末尾換行符
f.close()

輸出:(註意每行末尾的換行符

2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}


2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap


2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator

2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state ‘stopping‘

2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}

===========================================================================================

f = open(‘log.txt‘,‘r‘)
for line in f.readlines():
    print(line.strip())
f.close()

輸出:

2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}

2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap

2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator

2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state ‘stopping‘

2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}

2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN

===========================================================================================

f = open(‘log.txt‘,‘r‘)
print(f)
for i in f:
    print(i.strip())
f.close()

輸出:

<_io.TextIOWrapper name=‘log.txt‘ mode=‘r‘ encoding=‘cp936‘>

2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}

2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap

2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator

2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state ‘stopping‘

2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}

2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN

===========================================================================================

n = 0
f = open(‘log.txt‘,‘r‘)
for i in f:
    if n == 3:
        i = ‘‘.join([i.strip(),‘ this is line 4‘])
    print(i.strip())
    n += 1
f.close()

輸出:

2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}

2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap

2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator

2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state ‘stopping‘ this is line 4

2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}

2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN

===========================================================================================


tell和seek

f = open(‘log.txt‘,‘r‘)
print(f.read(25))
print(f.tell())  #取出光標所在位置
print(f.seek(0))  #移動光標到指定的位置
print(f.read(50))
f.close()

輸出:

2017-03-24 11:25:06:349 -

25

0

2017-03-24 11:25:06:349 - info: [debug] [AndroidBo

註意:read後不管是中文字符還是英文字符,都統一算一個單位,read(6),此刻就讀了6個中文字符;而seek和tell對於英文字符就是占一個,中文字符占三個,區分與read()的不同.

===========================================================================================


flush:同步把數據從緩存移動到磁盤上去

#進度條實例
import sys,time
for i in range(30):
    sys.stdout.write("*")
    sys.stdout.flush()
    time.sleep(0.1)

#print的flush
import sys,time
for i in range(30):
    print(‘*‘,end=‘‘,flush=True)
    time.sleep(0.1)

===========================================================================================

其他擴展:

#truncate():截斷數據(不能在r模式下)
#在w模式下:先清空,再寫,再截斷
#在a模式下:直接將指定位置後的內容截斷
# r+:光標默認在0位置開始寫,從0開始覆蓋數據
# w+:先清空,再寫讀
# a+:光標默認在最後位置

===========================================================================================

with:

為了避免打開文件後忘記關閉,可以通過管理上下文,即:

with open(‘log.txt‘,‘r‘) as f:
    print(f.readline())

在Python 2.7 後,with又支持同時對多個文件的上下文進行管理,即:如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。

#with 同時管理多個文件對象
with open(‘log1‘,‘r‘) as f_read, open(‘log2‘,‘w‘) as f_write:
    for line in f_read:
        f_write.write(line)


本文出自 “on_the_road” 博客,請務必保留此出處http://cqtesting.blog.51cto.com/8685091/1959698

python學習筆記文件操作(六)