Operation processing of documents

1, file operations process:

1.1 Definition file:

File is the operating system to the application to operate the hard disk interface, the user or application file operation is initiated calls to the operating system, then the specific operation by the operating system on the hard drive.

1.2 Basic operation flow of file:

1. 打开文件,由应用程序向操作系统发起系统调用open(...),操作系统打开该文件,对应一块硬盘空间,并返回一个文件对象赋值给一个变量f
#open('文件的路径',mode = "打开文件的模式",encoding ="操作文件的字符编码")
#默认打开文件的模式是rt模式,r代表只读,t代表文本文件,默认的打开文件的编码是: win:gbk  linux:utf-8  mac: utf-8
f = open('a.txt',mode='r',encoding='utf-8') #默认打开模式就为r

2. 调用文件对象下的读/写方法,会被操作系统转换为读/写硬盘的操作
data = f.read()

3. 向操作系统发起关闭文件的请求,回收系统资源
f.close()

2, the relative and absolute paths:

Relative path : a.txt must match the current py file in the same directory (usually using a relative path)
Absolute path : the path to find the root directory

3, resource recovery and with context management

Open a resource file contains two parts: an application and operating system variables f open files. When a file operation is completed, it must be fully recovered and the two parts of the resource file, the recovery process is:

1、f.close() #回收操作系统打开的文件资源
2、del f #回收应用程序级的变量

After which del f must occur in f.close (), which would otherwise cause the operating system to open the file can not be closed, in vain footprint, and automatic garbage collection mechanism python determined that we need to consider del f, which requires us, after the operation is complete file, we must remember f.close ().

you can automatically help with the recovery of the operating system resources without their own operations

with open('a.txt',mode='r',encoding='utf-8') as f:      

可用with同时打开多个文件,用逗号分隔开即可
with open('a.txt','r') as f1,open('b.txt','r') as f2: 

4, open the file of three modes:

r:只读    注意:当要打开的文件不存在时,会报错
with open('a.txt',mode='r',encoding='utf-8') as f:      #with 可以不用关心关文件了
    print(f.read())    #读取文件,一次性读出所有数据
    print(f.readline())  #一行行读,执行一次,打印一行内容
    print(f.readlines())    #返回成列表的形式
    print(f.readable())    #判断文件是否可读


with open('a.txt',mode='r',encoding='utf-8') as f:              
    for line in f:
        print(line,end="")   #文本文件里本身就有隐藏的换行符,而print又自带就有一个换行符,所以每行之间有空行
w:只写      如果文件不存在,则新建一个文件,如果文件内存在数据,会清空数据,重新写入 
f = open('a'.txt,mode='w',encoding='utf-8')
print(f.write())
print(f.writable())   #判断文件是否可写
print(f.writelines())    #for+f.write()
a:追加写    如果文件内存在数据,会在已有数据后面追加数据,如果文件不存在,会新建一个文件写
f = open('a'.txt,mode='a',encoding='utf-8')
print(f.write())
了解:
r+  w+  a+:可读可写,且都保留自己的特性

5, document processing mode

Premise: t, b mode can not be used alone, must be used with / one r / w a

t(默认的):文本模式
        1. 读写文件都是以字符串为单位的
        2. 只能针对文本文件
        3. 必须指定encoding参数
    

b:二进制模式:
        1.读写文件都是以bytes/二进制为单位的
        2. 可以针对所有文件
        3. 一定不能指定encoding参数
            
强调:b模式对比t模式
    1、在操作纯文本文件方面t模式帮我们省去了编码与解码的环节,b模式则需要手动编码与解码,所以此时t模式更为方便
    2、针对非文本文件(如图片、视频、音频等)只能使用b模式


注意:1.rb模式读文本文件需要解码
with open('b.txt',mode='rb') as f:
    data=f.read()
    print(data.decode('utf-8'))
     2.wb模式写文本文件需要编码
with open('b.txt',mode='wb') as f:
    data='111'
    f.write(data.encode('utf-8'))

6, move the cursor within the control file

Premise: moving the file pointer is Bytes units, the only exception is read (n) at t mode, n-units of characters

with open('a.txt',mode='rt',encoding='utf-8') as f:
     data=f.read(3) # 读取3个字符
     
with open('b.txt', mode='rb') as f:
    print(f.read(3))  # 读取3个Bytes


f.seek  (offset,whence)
offset:相对偏移度(光标移动的位数)
whence:指定光标位置从何开始
    0:从文件开头
    1:从当前位置
    2:从文件末尾
    
强调:其中0模式可以在t或者b模式使用,而1跟2模式只能在b模式下用

如:
a.txt用utf-8编码,内容如下(abc各占1个字节,中文“你好”各占3个字节)
abc你好
# 0模式的使用
with open('a.txt',mode='rt',encoding='utf-8') as f:
    f.seek(3,0)     # 参照文件开头移动了3个字节
    print(f.tell()) # 查看当前文件指针距离文件开头的位置,输出结果为3
    print(f.read()) # 从第3个字节的位置读到文件末尾,输出结果为:你好
    # 注意:由于在t模式下,会将读取的内容自动解码,所以必须保证读取的内容是一个完整中文数据,否则解码失败

with open('a.txt',mode='rb') as f:
    f.seek(6,0)
    print(f.read().decode('utf-8')) #输出结果为: 好

# 1模式的使用:
with open('b.txt',mode='rb') as f:
    f.seek(3,1) # 从当前位置往后移动3个字节,而此时的当前位置就是文件开头
    print(f.tell()) # 输出结果为:3
    f.seek(4,1)     # 从当前位置往后移动4个字节,而此时的当前位置为3
    print(f.tell()) # 输出结果为:7
    

# 2模式的使用
with open('a.txt',mode='rb') as f:
    f.seek(0,2)     # 参照文件末尾移动0个字节, 即直接跳到文件末尾
    print(f.tell()) # 输出结果为:9
    f.seek(-3,2)     # 参照文件末尾往前移动了3个字节
    print(f.read().decode('utf-8')) # 输出结果为:好

6 modify, file

Emphasized :
1, hard disk space can not be modified, the update is the hard disk data overwrite the old content with new content
2, data in memory can be modified

文件a.txt原内容:
你好我是你爸爸

with open('a.txt',mode='r+t',encoding='utf-8') as f:
    f.seek(3)
    f.write('嗡嗡嗡')
    
文件a.txt修改后内容:
你嗡嗡嗡你爸爸

6.1 modify the way a file:

Realization of ideas:
1, the contents of the file is read into memory all at once send
2, the modification is completed in memory
3, and then write the results of the modified cover back to the original file

Advantages: In the file modification process the same data only one
drawback: will take up too much memory

with open('db.txt',mode='rt',encoding='utf-8') as f:
    data=f.read()

with open('db.txt',mode='wt',encoding='utf-8') as f:
    f.write(data.replace('kevin','SB'))

6.2 file modification way:

Realization of ideas:
1, to open the original file read, write way to open a temporary file
2, read the original content of the document line by line, write temporary files modified after ...
3, delete the original file, temporary file rename the original file name

Advantages: will not take up too much memory
Cons: file modification process saved two same data

import os
with open('b.txt',mode='rt',encoding='utf-8') as rf,\
        open('c.txt',mode = 'wt',encoding='utf-8') as wf:
    for line in rf:
        wf.write(line.replace('SB','kevin'))

os.remove('b.txt')
os.rename('c.txt','b.txt')

Guess you like

Origin www.cnblogs.com/baohanblog/p/12143032.html