1. File operation process
1、 open a file
open('C:\a.txt\nb\c\d.txt')
Solution 1: Recommend
open(r'C:\a.txt\nb\c\d.txt')
Solution two:
open('C:/a.txt/nb/c/d.txt')
f=open(r'aaa/a.txt',mode='rt') # The value of f is a variable, which occupies the memory space of the application
2、 Operating file:
To read/write files, the application's read and write requests to the file are all sending system calls to the operating system, and then the operating system controls the hard disk to read the input into the memory or write it to the hard disk
res=f.read()
3、 Close file
f.close() # Recycle operating system resources
f.read() # Variable f exists, but can no longer be read
2. Resource management and with context management
Opening a file contains two parts of resources: the variable f of the application and the file opened by the operating system.
After operating a file, the resources of these two parts must be recycled
There are usually two methods for recycling:
1 f.close()#Recover file resources opened by the operating system
2 del f # Recycle application resources
Among them, del f must occur after f.close(), otherwise the file opened by the operating system cannot be closed.
Python's garbage collection mechanism allows us to consider del f out of order, so we must remember that fclose() must be done after the operation,
But we are lazy or forgetful, so python has the with keyword to help us manage the context.
pass
open(‘b.txt’,mode=’rt’) as f2:
res1=f1.read()
res2=f2.read()
print(res1)
3. File operation mode
The modes of file read and write operations are
The mode of reading and writing content of the file is
t Text mode: 1. Read and write files are all based on character strings
Only for text files
The encoding parameter must be formulated
b Binary mode: 1. Read and write files are all based on bytes
Can target all files
Must not make encoding parameters
Emphasize: t and b cannot be used alone, they must be used in conjunction with r/w/a
Reference cases of each mode
1、 r (default operating mode):
Read-only mode, report an error when the file does not exist, and the file pointer jumps to the start position when the file exists
withopen('c.txt',mode='rt',encoding='utf-8')as f:print('First time reading'.center(50,'*'))
res=f.read() #Read everything from the hard disk into the memory
print(res)withopen('c.txt', mode='rt', encoding='utf-8')as f:print('Second reading'.center(50,'*'))
res1=f.read()print(res1)
Realize user authentication function
inp_username=input('your name : ').strip()
inp_password=input('your password : ').strip()withopen('user.txt',mode='rt',encoding='utf-8')as f:for line in f:
# print(line,end='') # egon:123\n
username,password=line.strip().split(':') #Compress assignment, take out the user name and password in the file
if inp_username == username and inp_password == password:print('login successfull')breakelse:print('Incorrect username or password')
Application ====》File
Application ====》Database Management Software=====》File
2、 w: Write only mode, when the file does not exist, an empty file will be created, when the file exists, the file will be cleared, and the pointer is at the beginning
withopen('d.txt',mode='wt',encoding='utf-8')as f:
# f.read() #Error, unreadable
# f.write('Chale\n')
# Emphasis 1:
# When the file is opened in w mode but not closed, continuous writing, the new content always follows the old one
# withopen('d.txt',mode='wt',encoding='utf-8')as f:
# f.write('Chale 1\n')
# f.write('Chale 2\n')
# f.write('Chale 3\n')
# Emphasis 2:
# If you reopen the file in w mode, the contents of the file will be cleared
# withopen('d.txt',mode='wt',encoding='utf-8')as f:
# f.write('Chale 1\n')
# withopen('d.txt',mode='wt',encoding='utf-8')as f:
# f.write('Chale 2\n')
# withopen('d.txt',mode='wt',encoding='utf-8')as f:
# f.write('Chale 3\n')
Case: w mode is used to create brand new files
File copy tool
Just read a file, write another file, and copy the read to the write.
# src_file=input('Source file path: ').strip()
# dst_file=input('Target file path: ').strip()
# withopen(r'{}'.format(src_file),mode='rt',encoding='utf-8')as f1,\
# open(r'{}'.format(dst_file),mode='wt',encoding='utf-8')as f2:
# res=f1.read()
# f2.write(res)
3、 a: Only append writing, an empty document will be created when the file does not exist, and the file pointer will be directly adjusted to the end when the file exists
withopen('e.txt',mode='at',encoding='utf-8')as f:
# f.read() #Report an error, cannot read
f.write('1\n')
f.write('2\n')
f.write('3\n')
Emphasize the similarities and differences between w mode and a mode:
1 The same point: When the open file is not closed, write continuously, and the newly written content will always follow the previously written content
2 Difference: reopening the file in a mode will not clear the original file content, and move the file pointer directly to the end of the file, and the newly written content will always be written at the end
Case: a mode is used to write new content on the basis of the original file memory, such as logging and registration
Registration function
name=input('your name : ')
pwd=input('your name : ')withopen('db.txt',mode='at',encoding='utf-8')as f:
f.write('{}:{}\n'.format(name,pwd))
Understand: + can not be used alone, must cooperate with r, w, a
r+, w+, a+: read and write
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts