什么是文件

文件是操作系统为用户提供的一个读写硬盘的虚拟单位,文件的操作就是文件的读、写。

操作过程:当我们双击文件 -<- 操作系统接收到指令请求(将用户或应用程序的读写操作转换成集体的硬盘指令) -<- 与硬盘、内存交互(读写数据) -<- 显示我们想要看到的数据。

Linux:在Linux系统中一切皆文件,应用程序也是文件

为什么要有文件

数据都保存在硬盘中,我们需要读写数据,就需要操作硬盘,而通过操作文件我们就可以操作硬盘(如果没有文件,就需要我们直接操作硬盘,这个是不现实的)。

Python如何用文件

Python使用open('文件路径')方法可以打开某个具体的文件.(用open打开文件后,我们还需要手动释放文件对操作系统的占用。)

fil=open(r'D:\pycharm学习笔记\test\test.txt')# r 是为了让路径中的\变的无意。
print(fil)
fil=open(r'D:\pycharm学习笔记\test\test.txt')# r 是为了让路径中的\变的无意。
print(fil)
<_io.TextIOWrapper name='D:\\pycharm学习笔记\\test\\test.txt' mode='r' encoding='cp936'>

读写文件的操作 .read()和.write()

1、文件操作的基础模式有三种(默认的操作模式为r模式):

r模式为read

w模式为write

a模式为append

2、文件读写内容的格式有两种(默认的读写内容的模式为b模式):

t模式为text

b模式为bytes

需要注意的是:t、b这两种模式均不能单独使用,都需要与r/w/a之一连用。

mode=‘r’标识读写格式只是读取,无法写入;mode='w'时,原文件内容会被新增内容直接覆盖;mode='a'时,新增内容会放在原文件内容尾部
文件数据只能读取,不能修改,其实当我们在原文件上添加数据时,它并不是原有的这个文件了,而是一个新的文件,只是系统做了优化,将新生成的文件替换成了原文件。

print(fil.read())
print(fil.read())
liuuliuulllllllllliuulllllllll
lllllllll
lllllllll


fil2 = open(r'D:\pycharm学习笔记\test\test.txt',mode='w',encoding='utf8')
fil2.write('嗨皮') 
fil3 = open(r'D:\pycharm学习笔记\test\test.txt','r',encoding= 'utf8')
print(fil3.read()) 

fil2 = open(r'D:\pycharm学习笔记\test\test.txt',mode='w',encoding='utf8')
fil2.write('嗨皮') 
fil3 = open(r'D:\pycharm学习笔记\test\test.txt','r',encoding= 'utf8')
print(fil3.read())
嗨皮
fil4 = open(r'D:\pycharm学习笔记\test\test.txt','a',encoding= 'utf8')
fil4.write('哈哈哈')
fil5 = open(r'D:\pycharm学习笔记\test\test.txt','r',encoding= 'utf8')
print(fil5.read())
fil2.close()
fil3.close()
fil4 = open(r'D:\pycharm学习笔记\test\test.txt','a',encoding= 'utf8')
fil4.write('哈哈哈')
fil5 = open(r'D:\pycharm学习笔记\test\test.txt','r',encoding= 'utf8')
print(fil5.read())
fil2.close()
fil3.close()
嗨皮哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
fil4.close()
fil5.close()
fil4.close()
fil5.close()

with管理文件操作上下文

之前我们使用open()方法操作文件,但是open打开文件后我们还需要手动释放文件对操作系统的占用。但是其实我们可以更方便的打开文件,即Python提供的上下文管理工具——with open().

with open(r'D:\pycharm学习笔记\test\test.txt','r',encoding='utf8') as f1:
    print(f1.read())
with open(r'D:\pycharm学习笔记\test\test.txt','r',encoding='utf8') as f1:
    print(f1.read())
嗨皮哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈

with open()方法不仅提供给自动释放操作系统占用的方法,并且with open 可以使用逗号分隔,一次性打开多个文件,实现文件的快速拷贝。

with open(r'D:\pycharm学习笔记\test\test.txt','r',encoding='utf8') as f2,\
        open(r'D:\pycharm学习笔记\test\test2.txt','w',encoding='utf8') as f3:
    f3.write(f2.read())
with open(r'D:\pycharm学习笔记\test\test.txt','r',encoding='utf8') as f2,\
        open(r'D:\pycharm学习笔记\test\test2.txt','w',encoding='utf8') as f3:
    f3.write(f2.read())

字符编码解码用到的翻译工具

中国:GBK(国标,在硬盘中)

外国:日本—Shift_JIS,美国ASCII,韩国Euc-kr (都存在硬盘中)

国际统一:Unicode(在内存中)进行编写,存取用UTF-8(硬盘中),Unicode与UTF-8为特例他们两个能够相互识别。

保证不乱码的核心法则就是,字符按照什么标准而编码的,就要按照什么标准解码,此处的标准指的就是字符编码。