Python basic 11 file operation, character encoding

Source: Internet
Author: User

Main content
    1. File operations
File operation mode for open file

The mode of opening the file is:

    • R, read-only mode (default).
    • W, write-only mode. "unreadable; not exist; create; delete content;"
    • A, append mode. "Readable; not exist" create; "only append content;"

"+" means you can read and write a file at the same time

    • r+, can read and write files. "readable; writable; can be added"
    • w+, write and read
    • A +, with a

r+: Readable and writable, if the file does not exist, error; w+: Readable and writable, if the file does not exist, create.

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)

    • Rb
    • Wb
    • Ab
Open File
open(‘song‘,encoding="utf-8")f.close()

Open the file song, the file handle has been kept in memory, the memory is assigned to an object.

Open time need to develop a file encoding set, inconsistent coding assembly error, such as on Windows default is Gbk,python is Utf-8 encoding.

Always remember to call the close () method of the file object after opening the file with open.

For example, to prevent the file from forgetting to close, you can also use the with () method. With IS by indentation

Read the file, read ()
open(‘song‘,encoding="utf-8")first_line = f.readline()print(‘first line:‘,first_line) #读一行print(‘我是分隔线‘.center(50,‘-‘))data = f.read()# 读取剩下的所有内容,文件大时不要用print(data) #打印文件f.close()

Open the file successfully, next, call the Read () method to read the entire contents of the file at one time, Python reads the content into memory. Calling read () reads the entire contents of the file at once, and if the file has 10G, the memory explodes and the file is not used when it is large.

ReadLine ()
    • Read the first line
open("song", ‘r‘,encoding="utf-8")print(f.readline())
    • Before reading five elements
open("song", ‘r‘,encoding="utf-8")for i in range(5): print(f.readline())
ReadLines ()

ReadLines () reads all the contents one at a time and returns the list by row

f = open ( ' R ', encoding=  "Utf-8") print (F.readlines ())  
f = open ( ' R ', encoding=  "Utf-8") for line in f. readlines ():  Print (Line.strip ()) #去掉前后空格         
for index,line in enumerate(f.readlines()): if index == 9: print(‘----我是分割线----‘) continue print(line.strip())

Supplemental Enumerate () usage, which traverses both the index and the elements such as:

list1 = ["这", "是", "一个", "测试"]for index, item in enumerate(list1): print index, item>>>0 这1 是2 一个3 测试

Enumerate can also receive the second parameter, which specifies the index starting value:

list1 = ["这", "是", "一个", "测试"]for index, item in enumerate(list1, 1): print index, item>>>1 这2 是3 一个4 测试

Call ReadLine () can read a line of content at a time, call ReadLines () to read all the content at once and return the list by row. Therefore, you need to decide how to call as needed.

If the file is small, read () One-time reading is the most convenient, if it is a configuration file, call ReadLines () is the most convenient

Tell ()

method returns the current position of the file, which is the current position of the file pointer.

#result : 0f = open("song", ‘r‘,encoding="utf-8")print(f.tell())
#result : 50print(f.read(50))print(f.tell())
Seek ()

method is used to move a file read pointer to a specified location

f =Open( ' R ', Encoding= "Utf-8") Span class= "hljs-function" >print (F.tell ()) print (F.readline ()) print (F.readline ()) print (F.readline ()) print (F.tell ()) F. seek ( print (F.readline ())   
Encoding ()

Returns the encoding method.

#result : utf-8f = open("song", ‘r‘, encoding="utf-8")print(f.encoding)
Fileno ()

Call the operating system's I/O to read and return the file descriptor that is the number.

#result : 3f = open("song", ‘r‘, encoding="utf-8")print(f.fileno())
Write file truncate ()

method is used to truncate a file, and if an optional parameter size is specified, the truncated file is a size character. If size is not specified, it is truncated from the current position, and all characters after the size are deleted after truncation.

song2 file contents: 1 Hello world2 Hello world3 Hello world4 Hello world5 Hello world6 Hello worldf = open (" Song2 ",  ' a ', Encoding= "Utf-8") F.seek (10) F.truncate (12) results song2: 1 Hello worl    
song2文件里的内容:1 hello world2 hello world3 hello world4 hello world5 hello world6 hello worldf = open("song2", ‘a‘,encoding="utf-8") f.seek(10)f.truncate()结果song2里内容为:1 hello wo
Flush ()

Generally, file stream operations contain buffering mechanisms, and the Write method does not write data directly to a file, but rather writes the memory to a specific buffer first.

Flush () is used to flush the buffer, and the data in the buffer is immediately written to the file, while emptying the buffer, without having to wait for the output buffer to be written passively. In general, the buffer is refreshed automatically when the file is closed, but sometimes you need to refresh it before closing, so you can use the flush () method.

Progress bar Exercises:

import sys,timefor i in range(50): sys.stdout.write("#") sys.stdout.flush() time.sleep(0.1)
Reference page

http://www.imooc.com/code/3269

Http://www.cnblogs.com/alex3714/articles/5717620.html

Http://www.cnblogs.com/chiguozi/p/5860364.html

Python basic 11 file operation, character encoding

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.