Python file operations

Source: Internet
Author: User

1. Initial knowledge of file operation
    • Normal operation (too low: no indentation, need to close, code is not aesthetically pleasing)
      f = open ('path', mode='r', encoding='utf-8 ')
      F.read ()
      F.close ()
    • Advanced operation (High Force lattice: There is indentation, do not need to close manually)
      With open ('path'R', encoding=' Utf-8 ' ) as F:    F.read ()

2. Read-only (R, RB)
  • R mode
    # F is called a file handle. We use this handle to manipulate the file. f = open ("21 days Learn python", mode="R", encoding="  UTF-8"= F.read ()  #  reads the data from the file. To the previous contentprint(content) F.close ()
    RB mode
    # RB reads bytes, except that bytes are not written encoding the rest of the same f = open ("21 days Learn python", mode="RB "  = f.read ()print(content) F.close ()

3. Write only (W, WB)
  • W mode
    #below this chestnut a bit sour, obviously is write mode, you have to read, please self- closingf = open ("Song list", mode="W", encoding="Utf-8") Content= F.read ()#in W mode. To read. It's going to go wrong.Print(content) F.write ("two tigers \ n") F.write ("Disturbed") F.flush ()#Refresh Pipelinef.close ()#Correct demonstration: This song is very good, who listens to who knowsf = open ("Song list", mode="W", encoding="Utf-8") s= ["it's windy.","Feng Dance nine days","Ice Age"] forEinchS:f.write (E) f.close ()
  • WB mode
    # like with b mode file operation mode, in line with my lazy temperament, do not write coding method # The following operation is also to go around, not to write Chinese characters in byte mode, finished with Pycharm Open File also TM is a Chinese character, the mystery of which only the Earth people know. f = open (" song list ", mode="WB") f.write ("  King Mao Lion ". Encode ("UTF-8")) F.flush () F.close () 

4. Append (A, AB)
  • a mode
     #   already pro, not much introduction.  f = open ( "  song single haha   ", Mode="  a   ", Encoding="  utf-8   " ) F.write ( "   and see the smoke.   " ) F.flush () f.close ()  

     

  • AB mode
    f = open (" song single haha. txt", mode="ab") f.write (" See the smoke again ". Encode ('utf-8')) F.flush () f.close ()

5. r+ Reading and writing
  • Plays r+ mode
    #Normal usagef = open ("Song list", mode="r+", encoding="UTF-8")#ReadContent =F.read ()Print(content)#WriteF.write ("Chengdu") F.flush () f.close ()#non-normal usagef = open ("Song list", mode="r+", encoding="UTF-8")#WriteF.write ("Cool Cool")#ReadContent =F.read ()Print(content) F.flush () F.close ()
    #深坑请注意: in r+ mode. If the content is read. No matter how much content is read. How much is the cursor shown? When you write to or manipulate the file, it is done at the end.

6. w+ Write Read
    • w+ mode
      #f = open ("doll ", mode="w+", encoding="  utf-8") f.write (" haha "=  F.read ()print(content) F.flush () f.close ()

7. A + write read (append read)
    • A + mode

      f = open ("doll ", mode="a+", encoding="utf-8 " ) f.write ("Teng "= f.read ()print (content) F.flush () f.close ()# in A + mode, whether read first or after. All data is not read.

      # There are some other operations with B. It's not much to repeat. is to change the characters to bytes. I am so lazy not to share, welcome to share the message.

8. Other methods of operation
  • Seek and tell good base
    # general operation of Seek F.seek (3)   #  moves the byte units in the UTF-8 file. If the Chinese move must be a multiple of 3 #  back to the beginning # Move to end # a yang finger of tell Print (F.tell ())  # tell me where the cursor is .

  • The Forgotten Truncate
    #Direct sticky exercise, use your own experience it#H, interception of the original document, interception of content: ' Gourd baby, gourd baby, '#1. Use Seek first, then intercept, a little superfluousf = open ('db1/Gourd Doll','r+', encoding='Utf-8') F.seek (24) f.truncate () f.seek (0)Print(F.read ()) F.flush () F.close ( )#2. Go directly to interceptf = open ('db1/Gourd Doll','r+', encoding='Utf-8') F.truncate (24)Print(F.read ()) F.flush () F.close ( )

9. Modification of documents
  • Get a wave of OS modules in advance
    #after the practice of the code, or dictation, focus, focus, the third time not to say! ImportOswith Open ('.. /db2/alex.txt','R', encoding='Utf-8') as F1, open ('.. /db2/alex_new.txt','W', encoding='Utf-8') as F2: forIinchf1:new_i=i.replace ('Alex','SB') F2.write (new_i) os.remove ('.. /db2/alex.txt') Os.rename ('.. /db2/alex_new.txt','.. /db2/alex.txt')

10. Relative path and absolute path
  • Absolute path. Finding files from the root directory of a disk
    # give me a chestnut: " d:/sylar/Oh. txt "

  • Relative path, relative to where your current file is located
    # give me another chestnut . " Oh. txt "

  • Return to the previous level:.. /
  • There are \t,\n,\r in the path. This ambiguous letter begins with a backslash, or directly preceded by a R
    # It is generally not recommended to start a word with a special meaning letter. # The first slash is used to escape ' Db\\test.txt ' # plus R, one step path2 = R'test.txt'

Python file operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.