Python file processing-read, write

Source: Internet
Author: User

The operations of file processing in Python include reading, writing, and modifying, and today we'll learn to read and write.

One, the read operation of the file

Example one:

#file read OperationsF= Open (file="First_blog.txt", mode ='R', encoding='GBK')#' R ' indicates read-only mode (open still for file), encoding = ' GBK ' means the original file is stored in ' GBK ', must be told to turn GBK to Unicode (Python3 encoding default Unicode)Data=F.read () # reads everything, the content is a string that has been convertedPrint(data) # Print to Screen f.close ()#The file must be closed after it is opened

‘‘‘
Output:
Write by Congcong

Hello world!

This is the first file I opened with Python.

‘‘‘

Example two:

#file binary read modeF= Open (file="First_blog.txt", mode ='RB')#' RB ' indicates binary read mode (the binary that the hard disk is stored in is opened as a second binary and no longer requires a specified encoding)Data=F.read ()Print(data) f.close ()" "output: B ' Write by Congcong\r\n\r\nhello world!\r\n\r\n\xd5\xe2\xca\xc7\xce\xd2\xd3\xc3python\xb4\xf2\xbf\xaa\xb5 \xc4\xb5\xda\xd2\xbb\xb8\xf6\xce\xc4\xbc\xfe\xa1\xa3\r\n\r\n '" "

Can you see the difference between example I and example two?

 The difference is that example two directly in RB mode open the file, RB refers to the binary mode, the data read into memory directly in the bytes format,

If you want to see the content, you also need to manually decode, so you do not need to specify the encoding during the file opening phase.

What if we don't know what code to save a file for?

Method One: Try to use a variety of coding, there is always a yes, indeed, but feel silly, there is no better way?

Method Two: import an external tool called Chardet (first you want to install the network, Python3 installation method command Line input: PIP3 install Chardet)

Import= chardet.detect (open ('first_blog.txt', mode='RB  '). Read ())print(res)' output: {' encoding ': ' GB2312 ', ' Confidence ': 0.99, ' language ': ' Chinese '}     confidence indicates confidence level
‘‘‘

Example three (cyclic reading):

#-*-coding:utf-8-*-F= Open ("For_line.txt", mode ='R', encoding='GBK') forLineinchF:#read by row    Print(line) f.close ()" "output: The keyboard alphabetical order is as follows: Qwertyuiop ASDFGHJKL zxcvbnm" "#reason for a blank line in the middle: print itself has a newline character

  Attention: 

    • When the file operation is opened in "R" or "RB" mode, it is read-only and cannot be written;
    • The files saved on your hard disk are 0101010 of some encoding, and you need to be aware of them when you open them:
      • RB, which reads directly from the file save native 0101010, represented in Python with byte type
      • R and encoding, read the hard disk 0101010, and according to encoding specified encoding format for segmentation, and then the "segmentation" after each paragraph 0101010 is converted to Unicode 010101010101, in Python with a string type representation

Second, the file write operation

Write operations can be divided into overwrite write files (' W ' and ' WB ') and append write files (' A ' and ' AB ') two major categories.

  1. Overwrite Write file

Examples are as follows:

#-*-coding:utf-8-*-#Note that when mode is ' W ', a new file is created, and when the file name is the same as the original, the original file is emptied and rewritten .f = open ("Write.txt", mode ='W', encoding='GBK')#the writing of ordinary filesF.write ('This is the first file I wrote in Python! '# automatically converts a written Unicode string into a GBK encoded binary string. F.close () F2= Open ("Write2.txt", mode ='WB')#write files in binary, mainly for the transmission of video pictures and other filesF2.write ("This is the first file to be written in binary! ". Encode ('GBK'))# Binary write must be added encode (), write Unicode encoded into the specified format of binary storage, Python3 default is Utf-8
F2.close ()  

Attention:

When a file overwrites a write operation, it is opened in "W" or "WB" mode, and can only be written, and the content will be emptied first while it is open.

When writing to the hard disk, you must be 0101010 of a certain encoding, which you need to be aware of when opening:

      • WB, the write needs to be directly passed in a code of 0100101, that is: byte type, binary write must be added encode () will write Unicode
      • W and encoding, a Unicode string is required for writing, and a Unicode string is converted to 010101010 of the encoding based on the encoding encoding developed

2. Append Write file

Examples are as follows:

 # Special Note When mode is ' a ', it is the file append mode, which is then the file f3 = Open ('write.txt', mode= ' a ', encoding='gbk') f3.write ('\ n This is the appended text 1!  ') # automatically converts a written Unicode string into a GBK encoded binary string. 

f3.write ('\ n This is the appended text 2! ')
 f3.write ('\ n This is the appended text 3!  ')
F3.close ()

f4 = open ('write3.txt', mode = 'ab' # append files in binary, mainly for the transmission of files such as video pictures
f4.write ('\ n This is a binary append file! '. Encode ('gbk') # binary Append write must also be added encode (), Encodes the write Unicode to a binary storage of the specified format, Python3 default is Utf-8
F4.close ()

File append write operation, open in "a" or "AB" mode, you can only append, that is: append content at the end of the original content

When writing to the hard disk, you must be 0101010 of a certain encoding, which you need to be aware of when opening:

      • AB, the write needs to be directly passed in a code of 0100101, that is: byte type, binary append write must add encode () will write the Unicode string into the specified encoded binary string, not specified when Python3 default utf-8.
      • A and encoding, a Unicode string is required for writing, and a Unicode string is converted to 010101010 of the encoding based on the encoding that encoding has developed

 Iii. file read-write (r+) and write-read (w+) Mixed mode

  1. Read and write files (r+)

Examples are as follows:

#-*-coding:utf-8-*-f = open (file= ' write.txt ', mode= ' r+ ', encoding= ' GBK ') # r+ indicates read-write mode print (' pre-read: \ n ', F.read ()) F.write (' This is the content in read/write mode \ n ') f.write (' This is the content in read/write mode \ n ') print (' Read and write: \ n ', F.read ()) f.close () ' "before Read and write: This is the first file I wrote in Python! This is the appended text 1! This is the appended text 2! This is the appended text 3! After reading and writing: "'

 Note: read-write mode can only view previously existing content, and the content of the write can not be read again (with the movement of the cursor, the next article will elaborate), open the File view, the written content has been appended to the last written before.

  2, the file write read (' w+ ', use very little, understand can)

Examples are as follows:

#-*-coding:utf-8-*-f = open (file= ' write.txt ', mode= ' w+ ', encoding= ' GBK ') print (' Pre-write: \ n ', F.read ()) F.write (' This is the write-in mode content \ n ') f.write (' This is the content of write-in mode \ n ') print (' write-read: \ n ', F.read ()) f.close () ' "before writing:"

 Note : The file's read-write mode will first empty the contents of the original file, then write what you are about to write, the equivalent of overwrite write, the difference is that you can view the content written,

You need to move the cursor position in the file. The next article in the common operation method will be fine.

  

    

  

Python file processing-read, write

Related Article

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.