python0.11-----File/encode and decode/pickle modules

Source: Internet
Author: User

File:
File read-write and C-compatible in Python, read-write on disk is done by the operating system, and normal programs cannot manipulate the disk. File reads and writes are done through the operating system object, which is called a file descriptor.

There are two types of file operations:

1. Open File
Open (Path,flag[,encoding][,errors])
path: Paths to open the file.
flag: Open mode.
r: Opens the file in a read-only manner. The (descriptor) pointer of the file is placed at the beginning of the file.
RB: Opens a file in binary format for read-only, and the file descriptor is placed at the beginning of the file.
r+: Opens a file for read-write, and the file descriptor is placed at the beginning.
w: Open file only for writing. If the file already exists, it will be overwritten, and if the file itself does not exist, a new file will be created.
WB: Open a file only for writing to binary. If the file already exists, it will be overwritten, and if the file itself does not exist, a new file will be created.
w+: Opens a file for read-write. If the file already exists, it will be overwritten, and if the file itself does not exist, a new file will be created.
A: Open a file for append. If the file exists, the file descriptor is placed at the end of the file. If the file itself does not exist, a new file is created.
A +: Opens a file for read-write. If the file exists, the file descriptor is placed at the end of the file. If the file itself does not exist, a new file is created. Note: Because the file descriptor is placed at the end of the file, the read file cannot read anything.

Encoding: Encoding method.
Errors: Error handling mode, ' ignore ' means that if the encoding and decoding inconsistent will not error, ' strict ' indicates that if the encoding and decoding inconsistent error.
Note: Network data is transmitted in binary. So there is ' WB ', ' RB '.

Example:
F=open (R ' C:\Users\yuliang\Desktop\Project\lrc.txt ', ' R ', encoding= ' utf-8 ', errors= ' ignore ')
Note: F represents a file that is already open.
2.1 Read the contents from the file:
#1. Read the full contents of the file: Str1=f.read (), at which point the file descriptor has reached the end of the file.
Note: If the file is large, there are more than 1G, then the contents of the file are all stored in the memory, so obviously not good.
#2. Reads the specified content: Str1=f.read (num), reading the number of num characters following the file descriptor, at which point the file descriptor moves the num character position to the right.
#3. Reads the entire line, including the ' \ n ' character: Str1=f.readline (), and the file descriptor is placed at the beginning of the next line. In addition, Str1=f.readline (num) functions like Str1=f.read (num), but it is seldom used.
#4. Read all the rows and return to the list: List1=f.readlines (). The file descriptor is placed at the end of the file. In addition, List=f.readlines (num), if a given number is greater than 0, reads the number of rows in the actual size. But it's seldom used.
#5. The location of the modified descriptor: F.seek (num). Indicates that the file descriptor is placed at the location of Num characters from the beginning of the file.

2.2 Write content to file:
#1 Write information str1 to buffer F1.write (STR1)
#2刷新缓冲区
F1.flush (): Writes the contents of the buffer directly to the file immediately. Without this statement, the contents of the buffer are written to the memory area when the file is closed. If the buffer is full, the buffer will be automatically written to the file immediately.

3. Close the file
F.close

#一个完整的过程
Try
F1=open (path, ' R ')
Print (F1.read ())
Finally
If F1: #若f1正常打开, it is off, otherwise it does not need to be closed.

Fi.close

#更简单的读取方式:
With open (path, ' R ') as F1:
Print (F1.read ())
If the file is opened successfully or fails, with the final file can be closed automatically.

#写内容的简单方式, no shutdown, no refresh
With open (path, ' a ') as F1:
F1.write (str)

Encoding and decoding:
With open (path, ' WB ', encoding= ' utf-8 ') as F1: #wb表示将存入文件的数据应该为字节类型.
F1.write (str1.encoding (' Utf-8 ')) #将字符串str1用utf-8 format is encoded into binary mode and written to the file. If not coded, then error: A Bytes-like object is required, not ' str '.


With open (path, ' RB ') as F1:
Date=f1.read () #读出来的是二进制文件, date is the byte type class ' bytes '.
The Newdate=date.decode (' Utf-8 ') #所以要将字节类型以utf-8 format is decoded to a string type. If you do not decode, you cannot get a normal string.

Note: If the file Save encoding format is utf-8, then reading the content in GBK format will be an error: ' GBK ' codec can ' t decode byte 0xae in position 40:illegal multibyte Seque nCE
errors= ' Ingnore ' ignores the encoding and decoding inconsistencies of open files, and the inability to ignore the errors that occur when binary files are encoded.

Pickle Module : Data persistence module. It can write list,tuple,dict,set data to a file.

Ways to use the Pickle module:
#打开文件: F1=open (Path, ' WB ')
#使用pickle模块存储数据: Pickle.dump (DATA,F1)
#关闭文件: F1.close ()
#打开文件: F2=open (Path, ' RB ')
#读取pickle文件内容:p ickle.load (F2)
#关闭文件: F2.close ()
Note: Because dump and load will convert other data types into binary byte classes, the file should be read and written in the form of ' WB ' and ' RB '. If the read is not in binary form, an error will be made: write () argument must be str, not bytes

python0.11-----File/encode and decode/pickle modules

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.