11 Document Processing Basics

1. Process of file operation

1. Open the file

 open('C:\a.txt\nb\c\d.txt')

 Solution 1: Recommended

 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 that occupies the memory space of the application

2. Operation file:

For reading / writing 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 memory or write to the hard disk

res=f.read()

3. Close the file

f.close ()  # Reclaim operating system resources

f.read () # Variable f exists, but it cannot be read anymore

2. Resource management and with context management

Opening a file contains two partial 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 recovered

There are usually two methods for recycling:

1 f.close () # Recycle file resources opened by the operating system

2 del f      # recycle application resources

 Among them, del f must occur after f.close (), otherwise it will cause the file opened by the operating system cannot be closed.

Python's garbage collection mechanism lets us consider del f out of order, so we must remember that we must fclose () after the operation,

But we are all lazy or forgetful, so python has the with keyword to help us manage the context.

1. with open('a.txt',mode='rt') as f1:# f1=open('a.txt',mode='rt')

    pass

2. with open('a.txt',mode='rt') as f1,\

          open('b.txt',mode='rt') as f2:

      res1=f1.read()

      res2=f2.read()

      print(res1)

Three. File operation mode

The file read and write operation modes are

r (default): read only

w: write only

a: write only

The modes of reading and writing content of files are

t Text mode: 1. Both read and write files are in strings

       2. Only for text files

       3. Encoding parameters must be formulated

b Binary mode: 1. Read and write files are in bytes

       2. Can target all files

       3. Must not formulate encoding parameters 

Emphasis: t and b cannot be used alone, and must be used in conjunction with r / w / a

 Reference case of each mode

 1. r (default operating mode):

Read-only mode, an error is reported when the file does not exist, and the file pointer jumps to the start position when the file exists

 with open('c.txt',mode='rt',encoding='utf-8') as f:

     print ('First read'.center (50,' * '))

     res = f.read () # Read all content from hard disk into memory

     print(res)

  with open('c.txt', mode='rt', encoding='utf-8') as f:

     print ('Second reading'.center (50,' * '))

     res1=f.read()

     print(res1)

Implement user authentication

 inp_username=input('your name>>: ').strip()

 inp_password=input('your password>>: ').strip()

 with open('user.txt',mode='rt',encoding='utf-8') as f:

     for line in f:

         # print(line,end='') # egon:123\n

         username, password = line.strip (). split (':') #Compression assignment, take out the username and password in the file

         if inp_username == username and inp_password == password:

             print('login successfull')

             break

     else:

         print ('wrong account or password')

 Application ====》 File

 Application ====》 Database Management Software =====》 File

 

2. w: write-only mode, an empty file will be created when the file does not exist, and the file will be cleared when the file exists, the pointer is at the starting position

 with open('d.txt',mode='wt',encoding='utf-8') as f:

    # f.read () # Error, unreadable

    # f.write ('rub le \ n') 

# Emphasis 1:

# When the file opened in w mode is not closed, continuous writing, the new content always follows the old

# with open('d.txt',mode='wt',encoding='utf-8') as f:

    f.write ('Clear 1 \ n')

    f.write ('Clear 2 \ n')

    f.write ('Clear 3 \ n')

# Emphasis 2:

# If you reopen the file in w mode, the file content will be cleared

# with open('d.txt',mode='wt',encoding='utf-8') as f:

    f.write ('Clear 1 \ n')

# with open('d.txt',mode='wt',encoding='utf-8') as f:

    f.write ('Clear 2 \ n')

# with open('d.txt',mode='wt',encoding='utf-8') as f:

    f.write ('Clear 3 \ n')

 Case: w mode is used to create brand new files

 File copy tool

It is to 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 ()

# with open(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 to write, 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

 with open('e.txt',mode='at',encoding='utf-8') as f:

     # f.read () # Error, can't 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 Similarities: When the opened file is not closed, continuous writing, the newly written content will always follow the previously written content

 2 Differences: reopen the file in a mode, it will not clear the original file content, it will 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, registration

 Registration function

 name=input('your name>>: ')

 pwd=input('your name>>: ')

 with open('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 +: readable and writable

Guess you like

Origin www.cnblogs.com/baozai168/p/12729031.html