python学习笔记文件操作

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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学习笔记文件操作的主要内容,如果未能解决你的问题,请参考以下文章

python学习day9笔记

python爬虫学习笔记-M3U8流视频数据爬虫

python学习笔记第二天

python学习笔记012——pdb调试

python学习笔记:文件操作和集合

python学习笔记文件操作