Python: Basic operations for files

1. Basic Operation of Files

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): 
  1. Format One

    • open

      file1 = open('demo1.txt','r')
      
    • operation

      file1.write('Hello Python !')
      
    • Close

      file1.close()
      
  2. Format 2

    • Open, operate, close within a structure (automatically close when finished)

      with open('demo1.txt','r') as file1:
          file1.write('Hello Python !')
      

2. Reading and Writing Mode

read-write modefunctionOriginal file existsThe original file does not exist
rreadAn exception occurredRead inside
wWrite inOverwrite original contentAutomatically create a file and write to it
aAppendAdd new input after original contentAutomatically create a file and write to it
  1. Copy the contents of a file

    • Read, assign a variable to extract data

      with open('demo1.txt','r') as file1:
          data = file1.read()   
      
    • Write the variable to complete the replication

      with open('demo2.txt','w') as file2:
          file2.write(data)
      
  2. Graphic data (picture.jpg) or video data (video.mp4)

    'rb': Hinder  b  Represents the meaning of bytes, because binary data is stored directly in graphics and videos
    'wb'
    'ab'
        
    
  3. Read and write plus

    'r+'   'w+'   'a+'
    'rb+'  'wb+'  'ab+'
    

3. Read and write operations

Character modeparameterReturn valueExplain
read()nothingAll Character Data in FileExcessive memory usage
read(20)Number specifies sizeNumber of character data specified in the fileCancel the end flag, that is, read empty characters
readline()nothingOne line of character data in the fileA line of character data is described by the terminator'\n'
readlines()nothingAll character data in the file becomes a list, and each row of character data is an elementA line of character data is described by the terminator'\n'
write()Character stringWrites the contents of a string to a file
writelines()Include words onlyStorage mode of character information (list, tuple, collection, dictionary)Write character information from storage model to file
  1. Read All

    #The contents of the'hello.txt'file
    hello
    hello hello
    hello hello hello
    
    #The code is as follows
    with open('hello.txt','r') as file1:
        data = file1.read()
        print(data)
    

    It will output in full format, but the disadvantage is that it consumes too much memory and can be solved in three ways

  2. Read with parameters

    with open('hello.txt','r') as file1:
        data = file1.read(7)
        print(data)
    
    #The output format is as follows: where a line break or space is also considered a character
    hello
    h
    

    If batch reading is required, the Convention parameter value is 1024

  3. Single Line Read

    with open('hello.txt','r') as file1:
        data = file1.readline()
        print(data)
    
    #The output format is as follows
    hello
    
  4. Multiline Read

    with open('hello.txt','r') as file1:
        data = file1.readlines()
        print(data)
    
    #The output format is as follows
    ['hello\n', 'hello hello\n', 'hello hello hello\n']
    

    The data is output as a list, with one element per line, including line breaks

  5. During copying files: write() corresponds to read(), writelines() corresponds to readlines()

  6. File Path

    • Absolute path: Start with a drive letter and write out the detailed path

      with open('F:\Python\Python Basic knowledge learning\Python Course Practice Exercise\demo1.txt','w') as file1:    file1.write(' hello world , hello python ')
      
    • Relative path: Read or create new files at the same directory level using the current location as a reference value

      with open('.\..\..\demo1.txt','w') as file1:    file1.write('hello python 2021')    with open('.\Practice\demo1.txt','w') as file1:    file1.write('hello python 2021')#       .\  :  Represents the directory at this level#       ..\ :  Represents the directory above the current directory#   \Exercise\: Represents writing under the Exercises folder in the current folder
      

IV. OS Modules

  • Function nameExplain
    rename (file 1, file 2)File rename: change the name of file 1 to file 2
    remove (file name)Delete Files
    mkdir (directory name)Create directory
    Rmdir (directory name)Delete Directory
    ......
  1. Import OS modules

    import os
    
  2. File rename with file location change

    os.rename('demo1.txt','.\..\demo2.txt') #Change the file name of demo1 to demo2 and move to the last directory
    
  3. Delete Files

    os.remove('.\..\demo2.txt')
    
  4. Create directory

    os.mkdir('.\..\Practice')
    
  5. Delete Directory

    os.rmdir('.\..\Practice')
    

Keywords: Python Pycharm crawler

Added by zorgon on Thu, 02 Sep 2021 20:00:46 +0300