day11 file operations (on)

First, what is the file

Operating system files are available to the user / application concepts of operation for a virtual hard disk / Interface

User / application

Operating system (file)

Computer hardware (hard disk)

Second, why use a file

  1. User / application data files can be permanently stored on the hard disk
  2. Operation is operating hard disk file
  3. User / application directly file operation, the file operation is invoked in the system to the operating system, by the operating system and then converted to the specific operation of the hard disk

Third, how to use the file

The basic flow of 3.1 file operations

#1.打开文件,由程序想操作系统发起系统调用open()操作系统打开该文件,等于在硬盘上开辟了一个空间并给一个返回值给f
f = open("a.txt",mode="rt",encoding="utf-8")
#2.调用文件对象的xx方法,会被操作系统转换成操作硬件的操作
data = f.read()
#3.在完成对文件的操作后需要关闭文件,以免对操作系统造成资源浪费

3.2 Recycling with context management

We can see by the above picture, open a file will take up two sections resources:

First, the application file to file object operations defined in memory space

Second, the operating system in order to build applications and open files hard link resources

So at the end of each file operations, we need to be part of the recovery of these two resources

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

Here you must close the file and then recover variable, otherwise it will not find the file not turn off, del f usually does not need to write, because there is garbage collection mechanism python, f.close () is equal to the corresponding variable value and f relations disconnected. So just remember that every time in the last write operation close. But still sometimes we may forget, so python order to facilitate the development of personnel, provided with keywords to manage context

Open the file with

with open("a.txt","rt",encoding="utf-8") as f:
    f.read()
#可以用with打开多个文件,用逗号分隔
with open("a.txt","rt") as f1,open("b.txt","w") as f2:
    pass

3.3 Specify text character encoding operation

The lesson we learned, do not let the file garbled, it is necessary Unicode codec used, what is necessary to keep what to take. If we do not specify which file to open what character encoding when opened, will use the operating system default is open.

mac, linux operating system default is utf-8

windows operating system is the default GBK

pycharm default we use to use utf-8 storage, this time we pycharm write a text in the Windows operating system if there is no definition of open character encoding of the text, it will open with GBK, it will error, as shown below

f = open("a.txt",r,encoding="utf-8")#正确写法

Fourth, the operation mode of the file

t text (default mode)

  1. The default is to str (unicode) units
  2. Text File
  3. Must be specified encoding = 'utf-8'

b Binary / bytes

4.1 file read and write operations of the control mode (t Mode)

  1. r (do not write default): Read-only
  2. w: Write only
  3. a: only additional write
  4. +:r+,w+,a+

4.1.1 Case 1: r mode

#r只读模式,文件不存在时报错,文件存在则把指针跳到开头
with open("a.txt",mode="rt",encoding="utf-8") as f:
    res = f.read()#把文件的所有内容都赋值给res
    print(res)
    
#小练习,实现登录功能
name_inp = input("your name>")
pwd_inp = input("your pws>")
with open("a.txt",mode="rt",encoding="utf-8") as f :
    for line in f:
        username,password = line.strip().split(":")
        if username == name_inp and password == pwd_inp:
            print("welcome")
            break
    else:
        print("账号名或者密码错误")

4.1.2 Case Two: w mode

#w只写模式,如果文件不存在则创建新文件,文件存在会清空文件,光标回到文件开头
with open('b.txt',mode='w',encoding='utf-8') as f:
    f.write('你好\n')
    f.write('我好\n') 
    f.write('大家好\n')
#强调:
# 1 在文件不关闭的情况下,连续的写入,后写的内容一定跟在前写内容的后面
# 2 如果重新以w模式打开文件,则会清空文件内容

4.1.3 Case 3: Use a pattern

#a值追加写模式:文件不存在则创建文件,文件存在则把光标跳到文件末尾
with open("a.txt",mode="a",encoding="utf-8") as f :
    f.write("aaa")
#w模式和a模式的异同:
#相同点:打开文件不关闭的情况下,连续写入新内容,新写的内容会跟在之前写的后面
#不同点:w模式打开文件会清空文件,a模式只会让光标跳到最后
#练习:实现注册功能:

username = input("请输入注册的用户名:")
password = input("请输入注册的密码:")
with open("a.txt",mode="a",encoding="utf-8") as f :
    f.write("\n{}:{}".format(username,password))

4.1.4 Case Four: + mode is used (to know)

r +, w +, a + is readable and writable, but usually not with

Guess you like

Origin www.cnblogs.com/hz2lxt/p/12486517.html