5 python--file Processing

Source: Internet
Author: User

One, the file operation

#打开文件需要几步
#1. Open File
F=open (' 1.txt ', ' R ', encoding= ' utf-8 ')
#2. File operation (read or write), manipulate file handle by handle = open (' File path ', ' mode ')
File=f.read ()
#3. Closing files
F.close ()

Second, read the file

F=open (filename,mode,encoding)

# FileName: Indicates file name

# mode: Indicates the format of the open file

# Encoding: Indicates an open encoding format

 import   CODECSF  =codecs.open ( " 1.txt  "  Span style= "COLOR: #000000" >) text  =f.read ()  print   =text.replace ( " 1   ", "  a   " )  print   (Result)  #   print (F.read ())  print   (dir (f)) F.close ()  
View Code

#codecs模块只在python2中有, Python3 directly within the Open function (no need to import the module)

Third, File open mode

Common File Open mode:

R: Read-only open, file default open mode
W: file does not exist will be created, if present, overwrite source file (not append)
A: Only append mode is open (cannot read)
r+: Read/write mode (write is append)---> Common
A +: Append read/write
w+: Read-write mode (same as append)----> infrequently used
RB: Binary read mode (generally used for network transmission of data, because the network transmission is based on binary format, so must use B) Python 2.x is can be transmitted with STR
R+b: Open in binary read/write mode
W+b: Open in binary write mode
A+b: Open in binary append and read mode
B: Using binary mode (special files need to be transmitted in text mode, B is recommended)

Encoding Conversion

f = open (' Test.txt ', ' RB ')
F.write (' Hello '. Encoding ())
It can be converted into binary by encoding

Built-in methods for files (Python3)

--for-----> Python 2.x, 3
View Code

  

f  =  open ( ' test.txt ' , ' RB ' ) f.write ( hello ' .encoding ()) 通过encoding就可以转换成二进制

5 python--file Processing

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.