前面我们写过这么多的程序,大家有没有思考一个问题:如果我们程序关闭了,上次计算的结果还存在吗?如果三天前计算出来的结果又需要使用了,我们怎么办呢?这就要提到我们文件的概念了。
一、什么叫文件
文件是以硬盘为载体存储在计算机上的信息集合。计算机中的文件可以是文档、程序、快捷方式或设备。每一个文件都有一个文件名,文件名由名称和扩展名组成。名称是我们给每个文件起的名称,扩展名代表每个文件的类型。比如我们Python的源代码扩展名就是.py。以下是常见的文件扩展名:
图片文件 .jpg .png .bmp
文本文件 .txt
文档文件 .doc .docx .wps
表格文件 .xls .xlsx .et
音频文件 .mp3 .wav .wma
视频文件 .mp4 .mov .avi .mkv
文件最大的特点是保存在硬盘上,而我们之前编写的程序是在内存中运行的,程序运行结束后,内存中临时保存的内容就会被释放掉。
二、Python中文件的打开和关闭
Python中内置函数open()可以打开一个文件,它接收两个参数:文件名和打开方式。而文件的close()方法可以关闭文件,使用方法如下:
<变量名> = open('<文件名>', '<打开方式>')
<变量名>.close()
文件的打开方式有如下几种:
打开方式 | 含义 |
r | 只读模式,若文件不存在,程序报错 |
w | 覆盖写模式,若文件不存在则创建新文件,若文件存在则完全覆盖原内容 |
x | 创建写模式,若文件不存在则创建新文件,若文件存在则程序报错 |
a | 追加写模式,若文件不存在则创建新文件,若文件存在则在最后追加内容 |
+ | 与r/w/x/a一同使用,在原功能的基础上增加同时读写功能 |
目前阶段,我们需要掌握“只读”(r)和“覆盖写”(w)两种模式。分别用于读文件和写文件。
三、Python文件内容的读取
读取文件时,我们需要使用'r'方式打开一个文件。本部分的内容我们假设在电脑D盘根目录下有test.txt文件,文件的内容如下:
3.1 read()方法
read()方法可以一次性读取文件中所有内容,并保存到字符串中。我们看具体的例子:
f = open(r'D:test.txt', 'r')
s = f.read() #从指针所在的位置读到文件末尾
f.close()
print(s)
'''
打印结果:
hello python!
hello world!
'''
read()方法还有一个参数,参数内容为读取内容的字节数。我们看下面的例子:
f = open(r'D:test.txt', 'r')
s1 = f.read(15) # 从指针所在的位置读15个字节
s2 = f.read() # 从指针所在的位置读到文件结尾
f.close()
print(s1)
print(s2)
'''
打印结果:
hello python!
h
ello world!
'''
第一次运行时,读取了15个字节,到字母“h”结束,第二次读取时,从“h”后面开始读。如果我们第一次就读取了全部的,第二次再使用read()将无法读取到任何内容,因为读取指针已经到了文末。
f = open(r'D:test.txt', 'r')
s1 = f.read() # 读取文件中所有的内容
s2 = f.read() # 读取到0个字节,文件指针已经读到文件尾部
f.close()
print(s1)
print(s2)
'''
打印结果:
hello python!
hello world!
'''
如果我们已经读取过一次文件,想要回到开始重新读取,需要使用seek()方法,我们看具体的使用:
f = open(r'D:test.txt', 'r')
s1 = f.read() # 读取文件中所有的内容
f.seek(0)
s2 = f.read() # 读取到0个字节,文件指针已经读到文件尾部
f.close()
print(s1)
print(s2)
'''
打印结果:
hello python!
hello world!
hello python!
hello world!
'''
seek()方法可以调整文件读取指针的位置。
3.2 readline()方法
readline()方法可以读取文件中一行的内容,读取到“n”时,停止读取。我们看下面的例子:
f = open(r'D:test.txt', 'r')
s1 = f.readline() # 一次读取一行
s2 = f.readline() # 一次读取一行
f.close()
print(s1)
print(s2)
'''
打印结果:
hello python!
hello world!
'''
注意:每行读取的内容包含'n'。
3.3 readlines()方法
readlines()方法可以一次性读取文件的内容,并按行将内容存到列表中。我们看下面的例子:
f = open(r'D:test.txt', 'r')
list1 = f.readlines() #按行读取整个文件,放到列表中
f.close()
print(list1)
'''
打印内容:
['hello python!n', 'hello world!']
'''
四、Python中文件内容的写入
写入文件时,我们需要使用'w'方式打开一个文件。
4.1 write()方法
write()方法的参数是一个字符串,将字符串写入文件中。我们看下面的例子:
s = "Hello python!nHello world!nThis is the python world!"
f = open(r"D:test.txt", "w")
f.write(s)
f.close()
程序执行后,文件的内容如下:
4.2 writelines()方法
writelines()函数的参数可以是字符串,也可以是字符序列,并将字符序列写入文件中。我们看下面的例子:
list1 = ["Hello python!n", "Hello world!n", "Hello everyone!n"]
f = open(r"D:test.txt", "w")
f.writelines(list1)
f.close()
程序执行后,文件的内容如下:
有同学会问,这个列表中的元素字符串自带换行符,如果不带换行符,我们该怎么处理呢?这里教大家一个最简便的方法:
list1 = ["Hello python!", "Hello world!", "Hello everyone!"]
f = open(r"D:test.txt", "w")
f.writelines(i + 'n' for i in list1)
f.close()
五、含有中文的文件读写
前面将的文件读写都是使用的英文字母,如果大家善于尝试,在文本文件中输入中文,就会发现读取文件时程序可能就报错了。这是因为文件的字符编码问题。要解决这个问题,我们首先得知道文件中使用的是什么字符编码,在open()中加入encoding=编码的参数,我们看一下具体的写法:
f = open(r'D:test.txt', 'r', encoding='gbk')
s = f.read()
f.close()
print(s)
六、使用with子语句打开文件
前面我们打开文件都是使用的open()和close()的组合,这样操作符合人们的正常思维,打开文件,读取或写入,保存后关闭。但是如果忘记写关闭语句,文件将会一直被占用。因此,Python中还有一种使用with子语句打开文件的方式。文件操作的内容写在子语句的代码块中,代码块执行结束文件自动关闭。
我们看一下with子语句如何书写:
with open(r'D:test.txt', 'r') as f:
s = f.read()
print(s)
这里以读取文件为例,写入文件也是一样的写法。注意代码块一定要缩进。这样写就不再需要使用写close()方法,文件操作的方法写法与上面完全一致。
七、课后思考题
编程题:
在文本文件“poem.txt”中,有如下内容:
Very quietly I take my leave
As quietly as I came here;
Quietly I wave goodbye
To the rosy clouds in the western sky.
The golden willows by the riversideAre young brides in the setting sun;
Their reflections on the shimmering waves
Always linger in the depth of my heart.
The floating heart growing in the sludge
Sways leisurely under the water;
In the gentle waves of Cambridge
I would be a water plant!
That pool under the shade of elm trees
Holds not water but the rainbow from the sky;
Shattered to pieces among the duckweeds
Is the sediment of a rainbow-like dream?
To seek a dream? Just to pole a boat upstreamTo where the green grass is more verdant;
Or to have the boat fully loaded with starlight
And sing aloud in the splendour of starlight.
But I cannot sing aloud
Quietness is my farewell music;
Even summer insects keep silence for me
Silent is Cambridge tonight!
Very quietly I take my leave
As quietly as I came here;
Gently I flick my sleeves
Not even a wisp of cloud will I bring away.
1、将文件的内容读取到字符串中,并打印输出
2、在文本文件的开头加两行内容:
Say goodbye to Cambridge Again
Xu Zhimo
并重新保存poem.txt。
八、 上节课思考题答案
参考代码:
s = input()
r = ''
for i in ns:
a = ord(i)
# 从字母A到字母W都是ASCII码加3,偏移到后面的第三个字符
if (a >= 65 and a <= 87) or (a >= 97 and a <= 119):
a += 3
r += chr(a)
# 字母XYZ需要偏移到ABC,加3再减26
elif (a >= 88 and a <= 90) or (a >=120 and a <= 122):
a = a + 3 - 26
r += chr(a)
#除字母外,其他字符保持不变
else:
r += i
print(r)