Python学习之路5☞文件处理

一.文件处理流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件
 1 正趣果上果
 2 Interesting fruit fruit
 3 
 4 词:郭婞
 5 曲:陈粒
 6 编曲/混音/和声:燕池
 7 萧:吗子
 8 Words: Guo 婞
 9 Song: Chen tablets
10 Arrange / Mix / Harmony: Yan Chi
11 Xiao: Well
12 
13 你佩桃木降妖剑
14 他会一招不要脸
15 哇呀呀呀
16 输在没有钱
17 输在没有钱
18 You wear peach down demon sword
19 He will shamelessly
20 Wow yeah
21 Lost in the absence of money
22 Lost in the absence of money
23 
24 你愿终老不羡仙
25 谁料温柔终老空了长生殿
26 哎唏唏唏
27 败给好容颜
28 败给好容颜
29 You would like to end the old do not envy cents
30 Mummy gentle death of the empty palace
31 Hey Xi Xi
32 Lost to good appearance
33 Lost to good appearance
34 
35 人生在世三万天
36 趣果有间 孤独无解
37 苦练含笑半步癫
38 呐我去给你煮碗面
39 Life is thirty thousand days
40 Fun fruit there is no solution between solitude
41 Hard practicing smiling half-step epilepsy
42 I'll go and cook your bowl
43 
44 心怀啮雪大志愿
45 被人称作小可怜
46 呜呼呼呼
47 突样未成年
48 突样未成年
49 Heart of the snow big volunteer
50 Was called a small pitiful
51 Alas
52 Sudden sample of minor
53 Sudden sample of minor
54 
55 本欲歃血定风月
56 乌飞兔走光阴只负尾生约
57 噫嘘嘘嘘
58 真心怕火炼
59 真心也怕火炼
60 The desire to set the wind blood months
61 Wu Flying Rabbit only time to bear the tail about
62 噫 boo boo
63 Really afraid of fire refining
64 Really afraid of fire
65 
66 人生在世三万天
67 趣果有间 孤独无解
68 苦练含笑半步癫
69 呐我去给你煮碗面
70 Life is thirty thousand days
71 Fun fruit there is no solution between solitude
72 Hard practicing smiling half-step epilepsy
73 I'll go and cook your bowl
74 
75 是非对错二十念
76 十方观遍 庸人恋阙
77 自学睡梦罗汉拳
78 吓 冇知酱紫好危险
79 Right and wrong twenty read
80 square view over the Yong love Que
81 Self - study sleep Lohan boxing
82 Scare know that a good risk of Jiang Xi
示范文件内容

二.基本操作

2.1 文件操作基本流程初探

1 f = open('chenli.txt') #打开文件
2 first_line = f.readline()
3 print('first line:',first_line) #读一行
4 print('我是分隔线'.center(50,'-'))
5 data = f.read()# 读取剩下的所有内容,文件大时不要用
6 print(data) #打印读取内容
7  
8 f.close() #关闭文件

2.2 文件编码

文件保存编码如下

此刻错误的打开方式
f=open('chenli.txt',encoding='utf-8')
f.read() 

正确的打开方式
#不指定打开编码,默认使用操作系统的编码,windows为gbk,linux为utf-8,与解释器编码无关
f=open('chenli.txt',encoding='gbk') #在windows中默认使用的也是gbk编码,此时不指定编码也行
f.read()

2.3 文件打开模式

1 文件句柄 = open('文件路径', '模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
  • w,只写模式【不可读;不存在则创建;存在则清空内容】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

2.4 文件内置函数flush

 

flush原理:

  1. 文件操作是通过软件将文件从硬盘读到内存
  2. 写入文件的操作也都是存入内存缓冲区buffer(内存速度快于硬盘,如果写入文件的数据都从内存刷到硬盘,内存与硬盘的速度延迟会被无限放大,效率变低,所以要刷到硬盘的数据我们统一往内存的一小块空间即buffer中放,一段时间后操作系统会将buffer中数据一次性刷到硬盘)
  3. flush即,强制将写入的数据刷到硬盘

滚动条:

1 import sys,time
2 
3 for i in  range(10):
4     sys.stdout.write('#')
5     sys.stdout.flush()
6     time.sleep(0.2)

2.5 文件内光标内置函数

 read & readline & readlines:

 1 # 打开文件
 2 f = open("text", "r+")
 3 
 4 print(f.read(2)) #读取字节到字符串中,有可选参数size,默认是-1,如果为-1或复数则文件将会被读取到文件末尾。
 5 #输出结果为: 12
 6 
 7 print(f.readline(2)) #读取文件的一行,包括行结束符。同read()也有个可选参数size。
 8 #输出结果: 34
 9 
10 print(f.readline()) #读取一行中剩余内容
11 #输出结果:567890
12 
13 print(f.readlines())#读取所有(剩余的)然后将它们作为字符串列表返回,它有个可选参数sizhint代表返回的最大字大小
14 #输出结果:['abcde
', 'ABCDE']

seek:seek(offset,where)

seek(offset,where):  where=0从起始位置移动,1从当前位置移动,2从结束位置移动。当有换行时,会被换行截断。seek()无返回值,故值为None

示例:

1 f.seek(1,0) #从开始位置即文件首行首个字符开始移动一个字符
2 print(f.tell()) #此时tell()为1
3 print(f.readline()) #读取当前行的内容,即文件的第一行,从第二个字符开始读
4 #读取结果为:2345

tell:

文件的当前位置,即tell是获得文件指针位置,受seek、readline、read、readlines影响,不受truncate影响

示例:

1 f=open('text','w+') #文件以w+方式打开,则源文件被清空
2 print(f.tell())      #源文件被清空,故此时输出为0
3 
4 f.write("12345")  #在文件中写入12345,故站用5个字符
5 print(f.tell())    #此时tell()=5

truncate:

 1 示例一:
 2 # 打开文件
 3 f = open("text", "r+")
 4 line = f.readline()
 5 print(line)
 6 
 7 #输出结果:12345
 8 
 9 # 截断剩下的字符串
10 f.truncate()
11 
12 # 尝试再次读取数据
13 line = f.readline()
14 print(line)
15 #输出结果为空
16 
17 # 关闭文件
18 f.close()
19 
20 示例二:
21 # 打开文件
22 f = open("text", "r+")
23 
24 # 截取3个字节
25 f.truncate(3)
26 
27 msg = f.read()
28 print(msg)
29 
30 输出结果:123
31 # 关闭文件
32 f.close()

2.6 open函数详解

 1. open()语法


open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
open函数有很多的参数,常用的是file,mode和encoding
file文件位置,需要加引号
mode文件打开模式,见下面3
buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小;
encoding表示的是返回的数据采用何种编码,一般采用utf8或者gbk;
errors的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。
newline可以取的值有None, , , ”, ‘ ',用于区分换行符,但是这个参数只对文本模式有效;
closefd的取值,是与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。

2. Python中file()与open()区别
两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两种文件打开方式有本质的区别,file为文件类,用file()来打开文件,相当于这是在构造文件类,而用open()打开文件,是用python的内建函数来操作,建议使用open

3. 参数mode的基本取值

Character Meaning
‘r' open for reading (default)
‘w' open for writing, truncating the file first
‘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 (for backwards compatibility; should not be used in new code)

r、w、a为打开文件的基本模式,对应着只读、只写、追加模式;
b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用、

常见的mode取值组合

r或rt 默认模式,文本模式读
rb   二进制文件
    
w或wt 文本模式写,打开前文件存储被清空
wb  二进制写,文件存储同样被清空
    
a  追加模式,只能写在文件末尾
a+ 可读写模式,写只能写在文件末尾
    
w+ 可读写,与a+的区别是要清空文件内容
r+ 可读写,与a+的区别是可以写到文件任何位置

2.7 上下文管理

with open('a.txt','w') as f:
    pass
with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
    data=read_f.read()
    write_f.write(data)

2.8 文件的修改

 1 import os
 2 with open('a.txt','r',encoding='utf-8') as read_f,
 3         open('.a.txt.swap','w',encoding='utf-8') as write_f:
 4     for line in read_f:
 5         if line.startswith('hello'):
 6             line='哈哈哈
'
 7         write_f.write(line)
 8 
 9 os.remove('a.txt')
10 os.rename('.a.txt.swap','a.txt')
原文地址:https://www.cnblogs.com/Vae1242/p/6940983.html