Python foundation – file processing

Time:2020-2-12

File processing

Three questions about documents: what are documents? Why file? How to use documents?

  • File system is a tool provided by the operating system for us to operate the hard disk
  • File systems are used to hold data permanently

How to operate files

  • Relative path and absolute path

    • Relative path: fromCurrent path start, relative to the path to a base directory
    • Absolute path: fromThe root directory is the drive letterPath to start

    In programming, relative paths are recommended

  • Two methods of operating files

    • open

      Syntax:F = open ('filename path ', mode, encoding), to open a file.

      File path: relative path is recommended

      mode: there are three modes to open a file:rwa。 The two modes of general and processing files are applied.

      There are two modes for processing files:tandb

      encoding: open the file and operate the encoding settings of the file content

      #The first way to open it is to use f.close() to close system resources
      f = open("a.txt","r",encoding="utf-8")
      Data = f.read() -- read all contents of a.txt file
      Print (data) print the contents of the file
      f. Close() -- close operating system resources
      Pattern describe Characteristic
      rt Default mode, which can be abbreviated asr。 withText file and read onlyOpen file in If the file does not exist,Report errors
      wt Abbreviated asw。 withText file and write onlyMode open file If the file does not exist, create a new file; if there is data in the file,Rewrite the contents of the file
      at Abbreviated asaIn order toText file and write onlyMode open file If the file does not exist, create a new file; if there is data in the file,Append content after data
      rb withBinary characters and read onlyOpen file in If the file does not exist,Report errors
      wb withBinary characters and write onlyOpen file in If the file does not exist, create a new file; if there is data in the file,Rewrite the contents of the file
      ab withBinary characters and write onlyOpen file in If the file does not exist, create a new file; if there is data in the file,Append content after data
    • with open() as …:

      Syntax:With open (mode, encoding) as F:It is recommended to operate on files in this way, context sensitive open file. Advantage: it not only automatically reclaims system resources, but also can open the same file or multiple files in multiple modes at the same time.

      #The second mode, context sensitive mode, will automatically close system resources. This mode is recommended
      with open("a.txt","r",encoding="utf-8") as f:
          data = f.read()
          print(data)
      
      #Open multiple files at the same time, separated by commas
      with open("a.txt","r",encoding="utf-8")as rf,\
          open("b.txt","w",encoding="utf-8") as wf:
          data = f.read()
          wf.write(data)
  • Built in method of file processing

    #Contents of a.txt file
    Name: Sean
    Age: 18
    Gender: Male
    Description: the most handsome person in Shanghai Campus
    • read

      grammar Explain
      f.read() By default, all the contents of the file are read at one time; parameters are based on the mode of mode,If it ist, the number of characters to read the file; if yesb, bytes read from file
      f.readline() Only one line can be read at a time
      f.readlines() Read all the data into memory,Line break delimited list
      f.readable() Determine whether the file is readable and return the Boolean value
      #Mode: read only text mode, r = RT is read text
      with open("a.txt","r",encoding="utf-8") as f:
          Print (f.readable()) ා print result is: true
          Print (f.readline()) ා print result: Name: Sean
          Print (f.readlines()) ා the result is: list ['age: 18 \ n','gender: male \ n ','description: the most narcissistic person in Shanghai Campus']
          f. Seek (0,0) moves the cursor to the beginning of the file
          Print (f.read()) ා񖓿the result is: all content
      #Mode: read only byte mode, Rb is read bytes. Note: using byte mode, encoding parameter is not available
      with open("c.txt","rb") as f:
          Print (F "readable result: {f. readable()}") ා print result: true
          Print (F "read result: {f.read()}") (print result: binary bytes of all contents of the file
          f. Seek (0,0) moves the cursor to the beginning of the file
          Print (F "result of readLine: {f.readline()}") (print result: the binary byte of the first line record of the file content
          f.seek(0,0)
          Print (F "result of readLine: {f.readlines()}") (print result: binary byte in list form

      Print results:

      Python foundation - file processing

    • write

      grammar Explain
      f.write() Write data to file
      f.writelines takeElements of iteratable objects are in the form of stringsWrite to file. Equivalent to for + write()
      f.writeable Determine whether the file is writable and return the Boolean value
      #Write only text mode, empty the original content in the file, and rewrite the new content
      with open(r"a.txt","w",encoding="utf-8") as wf:
          Print (F "read or not: {WF. Readable()}")      
          Print (F "writable or not: {WF. Writable()}")
          WF. Write ("this is the new write using write \ n")
          WF. Writelines (["this is the content newly written with writelines 1 \ n", "this is the content newly written with writelines 2 \ n", "this is the content newly written with writelines 3 \ n"])) (the contents in the list will be spliced and written to the file.)
      
      #Verify that the contents are written to the a.txt file
      with open(r"a.txt","r",encoding="utf-8") as  rf:
          print(rf.read())

      Operation result

      Python foundation - file processing

      #Append text mode, keep the original content in the file, and append new data after it
      with open(r"a.txt","a",encoding="utf-8") as af:
          Print (F "read or not: {af.readable()}")
          Print (F "writable or not: {af.writable()}")
          Af.write ("this is what was written using append mode write \ n")
          Af.writelines (["this is the new content 1 written using append mode writelines", "this is the new content 2 written using append mode writelines", "this is the new content 3 written using append mode writelines"])
      #Verify that the contents are written to the a.txt file
      with open(r"a.txt","r",encoding="utf-8") as  rf:
          print(rf.read())

      Operation result

      1573219631390

    • Operation of cursor (pointer)

      grammar describe
      f.seek(offset,whence) Offset F: relative offset, that is, the number of digits the cursor moves,For bytes
      When: used to specify where the cursor position starts.
      Values can only be: 0 (beginning of file), 1 (current location), 2 (end of file).
      f.tell() Cursor position
  • Be careful:
    • In UTF-8, Chinese characters account for3bytes, English characters1bytes
    • In GBK, Chinese characters account for2bytes, English characters1bytes
    • When working with files,We must pay attention to the problem of coding rules, and remember the core of ensuring that there is no confusion: we can use whatever code we use to encode the stored data

The expansion of the Chinese people

Read files we learnedrwaIt’s pure mode, andr+w+a+Pattern. These three modes are set to read-write mode, and other features are the same as pure mode.