python--file Operations

Source: Internet
Author: User

  Blog Address: http://www.cnblogs.com/yudanqu/

First, read the document

How many steps will it take to install an elephant in a refrigerator? This is also a simple process for reading and writing files, opening files, reading files, and closing files.

Descriptor: File All operations involve descriptors, descriptors are cursors, reading data can be read backwards from the cursor, and so on.

1. Open File
Open (Path, flag[, encoding][, errors])
    • Path: The path of the file to open
    • flag: Open with
      • r    Open the file as read-only, the file's descriptor is placed at the beginning of the file
      • rb  to Binary Binary format opens a file for read-only, the file's descriptor is placed at the beginning of the file
      • r+  open a file for read-write, the file's descriptor is placed at the beginning of the file
      • w    Open a file for writing only, Create a new file if the file already exists that is not present
      • WB opens a file for write binary only, if the file already exists will overwrite, does not exist create a new file
      • w+ open a file for read-write, if the file already exists will overwrite, Does not exist create a new file
      • a    Open a file to append if the file exists, the file descriptor will be placed at the end of the file
      • a+  
    • Enco Ding: Encoding (General Utf-8)
    • errors: Error handling (typically not handled)
1 # Small Chestnuts 2 " R ", encoding="utf-8", errors="ignore")  3#  Ignore ignore error, generally do not write after two parameters
2. Read the contents of the file
1 #read the entire contents of a file2STR1 = F.read ()#read the file relatively small, large memory not fit3 4 #reads the specified number of characters (by characters)5STR2 = F.read (10)#A letter and a kanji are called one character6 7 #reads the entire line, including the "\ n" character8STR3 =D.readline ()9 Ten #reads the specified number of characters OneSTR4 = F.readline (10) A  - #reads all rows and returns the list -STR5 =F.readlines () the  - #returns the number of rows of the actual size byte if the given number is greater than 0 -STR6 = F.readlines (25)#For example, 25 bytes, each row has 10, then read two lines at this time -  + #Modify the location of the descriptor -F.seek (10)#change to the position of the first few characters
3. Close the file
1 f.close ()
4. Small chestnuts
 #   A complete procedure   Try  : F1.open (path,   " r  " , Encoding= "    Span style= "COLOR: #800000" >utf-8   " )  print   (F1.read ())  finally  :  if   F1:f1.close ()  #   tr Y...except...else...finally is the exception handling content, this example uses the part to indicate, if open reads the file partial error, as long as the file exists then closes the file at the end, this is a good habit, for example in the Linux operating system, Limit the number of open files to no more than 1024 if it exceeds, the file will not open.  

Of course, this kind of file is a bit cumbersome, then there are more convenient ways:

# Simple method:  "R", encoding="utf-8") as F2:     Print (F2.read ()) # With can put the file closed part of the implementation, regardless of whether we operate, whether there are errors, will be in the end to help us close the file, but also to avoid the problem we forget to close the file

Second, write the document
1f = open (path,"W")#First, open the file in write mode2 3 #The information is written to the buffer, not directly to the file, that is, we read the file when we write the file, no information is written at any time4F.write ("GLABSCUFN")5 6 #Flush Buffer (you can manually flush the buffer if you want to write to the file side)7F.flush ()#directly writes the data of the internal buffer immediately to the file instead of passively waiting for the file to close automatically flush buffer writes8 9 " "Ten refresh of buffer: One 1. Automatic refresh of file shutdown A 2, manual flush Refresh - 3, the buffer is full can also be automatically refreshed - 4, then there is the encounter ' \ n ' will also refresh the " " -  -F.close ()

Three, encoding and decoding 1, encoding
1 " WB " ) as F1:2     "asdasdasdasd"3     f1.write ( Str.encode ('utf-8'#  encoded with Utf-8
2. Decoding
1With open (path,"RB") as F2:2data =F2.read ()3New_data = Data.decode ("Utf-8")4     Print(Type (data))#class<byte>5     Print(Type (new_data))#class<str>6 #mainly in the case of having Chinese, other cases different codes may also be decoded correctly7 #if it's a binary string, remember to encode and decode

Iv. List,tuple,dict,set
1 ImportPickle#data Persistence module, which is the storage of data to disk2 3 #Write4MyList = [1,2,3,4,5,"Sadd"]5f = open (path,"WB")6 Pickle.dump (MyList, F)7 f.close ()8 9 #ReadTenF1 = open (path,"RB") OneTemplist =pickle.load (F1) A Print(templist) -F1.close ()

Yu Tanku (yudanqu)

Blog Address: http://www.cnblogs.com/yudanqu/

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.