Python Basics-File manipulation

Source: Internet
Author: User

Python3 File

  First, the basic incoming parameters of the method are affixed:

def Open (file, mode='r', Buffering=none, Encoding=none, Errors=none, newline= None, Closefd=true)

  In the actual operation, we are more commonly used are files,mode and encoding these 3 parameters

Let me introduce you individually:

    • file: The absolute path of the files we want to open, such as: "E:\ reading \python\8 month \0815\ Blog Park instance \xxx.xx"
    •  mode:  how to open
      • r: Read-only Mode " Default mode, the file must exist, no exception is thrown "
      •    w: Write-only mode" unreadable; not present "create; empty content"
      •    a: Append mode "readable;    not present" created; Append content only ", file pointer automatically moves to end of file.
      •     "+" means that a file can be read and written at the same time
      •    r+: Read and write "readable, Writable "
      •    w+: reads" Readable, writable ", removes the contents of the file, and then opens the file in read-write mode.
      •    a+: reads "Readable, writable", opens the file in read-write mode, and moves the file pointer to the end of the file.
      •     "B" means to operate in bytes, opening the file in binary mode instead of in text mode.
      •    RB: Read in binary mode
      •   WB: Write in binary mode
    •  Encoding: What code to open, this to note, if Garbled behavior occurs when the encoding is open and the actual encoding is not the same 

  Each action is described in detail next

    Read the file

f = open ("File.txt","R", encoding="utf-8  ")print(F.read ())" "" Run result this is the first line of the test file First998 """
Read the file

when you don't know the file code,

ImportCHARDETF= Open ("File.txt","RB") Data=F.read ()Print(Chardet.detect (data))#Run Result: {' encoding ': ' utf-8 ', ' confidence ': 0.99, ' language ': '}#when we do not know the file encoding format, we can import chardet this module#using its Detect method, a dictionary is returned, confidence is the probability of encoding the value that represents our encodingencoding = chardet.detect (data) ["encoding"]Print(Data.decode (encoding))
Find Code

Write a file

f = open ("File.txt","W", encoding="Utf-8") F.write ("This is the new content inserted") F.close () F= Open ("File.txt","R", encoding="Utf-8")Print(F.read ())#Run Result: This is the new content insertedf.close ()#when new content is inserted, the file deletes all previous content and re-writes the content
Write a file

Append

f = open ("File.txt","a", encoding="Utf-8") F.write ("This is the new content. ") F.close () F= Open ("File.txt","R", encoding="Utf-8")Print(F.read ())#Run Result: This is the old content. This is the new content. F.close ()
Append

Read/write mode

 f = open ( " file.txt  " ,  " r+  " , Encoding= " utf-8   " )  print  (F.read ()) #   The result is: This is the old content. This is the new content.  f.write ( "  This is the updated content.   " ) F.flush ()   #   immediately swipe the file contents from memory to hard disk  print  (F.read ()) Span style= "COLOR: #008000" >#   The result is: This is the old content. This is the new content. This is the content of the update.  f.close () 
read/write mode

Read-write mode

f = open ("File.txt""w+", encoding="utf-8 " )print(F.read ())  # The result is: Do not print anything f.write (" This is the updated content.  ")print# The result is: In the original file see:" This is the content of the update. " "This read-write mode can only read the contents of the f.close ()
read-write mode

file Operations Common Methods

#Open File Method 1:open ()f = open ("File.txt","r+")#Open File Method 2:with open () After this method operation is completed, the close () is automatically closed without needing close ()With open ("File.txt","r+") as F:f.read ()#reads the contents of the file (you can specify each character read)f = open ('File.txt','R', encoding='Utf-8') ret= F.read (8)Print(ret)#The result is: This is the file#read data (can specify number of characters to read), Save as List displayf = open ('File.txt','R', encoding='Utf-8') ret=F.readlines ()Print(ret)#The result is: [' This is what is inside the file. \ n ', ' Test ']f.close ()#reading a row of dataf = open ('File.txt','R', encoding='Utf-8') ret=F.readline ()Print(ret)#The result is: This is the contents of the file. f.close ()#determine if it is readable (non-readable, "No such file or directory:")f = open ('File.txt','R', encoding='Utf-8') ret=f.readable ()Print(ret)#The result is: #Truef.close ()#specify the position of the pointer in the filef = open ('File.txt','R', encoding='Utf-8') ret= F.read (8)#Read 8 characters FirstPrint(ret)#The result is: This is the fileF.seek (0)#then move the pointer to the beginning of the fileret = F.read (8)#after re-readingPrint(ret)#The result is: This is the filef.close ()#Get pointer positionf = open ('File.txt','R', encoding='Utf-8') ret= F.read (8)#Read 8 characters FirstPrint("Pointer position:%s"% F.tell ())#view current pointer position The result is: pointer position:16Print(ret) f.seek (0)#Reset specified to start bitPrint("Pointer position:%s"% F.tell ())#in the view pointer position the result is: pointer position:0f.close ()#flush File Internal buffersF.flush ()
Common methods for file operations

Python Basics-File manipulation

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.