Text read and write operations Python_

 

【demand】

1. Get the text content, extract usable information content of the information and a series of cleaning process

2. The algorithm outputs something, saved to a text file for easy use

【function】

In Python open () function is used to open the file, including text files

# Python3.x the open function prototype default = MODE 'R & lt' 
F = open (File, MODE = ' R & lt ' , Buffering = None, encoding = None, errors = None, NEWLINE = None, closefd = True)

file: file name (eg: 'example.txt') provided that the changed files in the current directory, if you do not need to add the path (eg: E: \\ 'example.txt')

mode: file open the way

# Is the most commonly used   ' R & lt ' : read-only (Requirement 1 available) 
 # Another is        ' A ' : additional writing (the original data is not clear text) 
 #                 ' W ' : writing, but the original data before it is cleared, re-create the text, covering 
# there are many other, less than the actual use, it is worth noting that such as 'b' binary reading and writing that is 'rb''wb' such as images or audio, etc.

buffering: Default is 0 unbuffered buffer 1 is line-buffered> byte buffer 1 is set by

Preliminary understanding: When writing text, is first written to the memory we can see in the open written to disk, the text is only written to disk.

Unbuffered -> text written directly into disk 

Buffer -> Content to be temporarily stored in memory, only f.close () to close the file, it will refresh the content saved to disk

## being less than the parameter

encoding: file encoding used 'utf-8' [Note] written in what way would open the way to what would otherwise be garbled

Text can be opened with Notepad ++, it can be seen above encoding files, and can change the encoding

 

 

 [Example]

# 文本写入
f = open("E:\Learning_2019\write_somthing.txt",mode= 'w',encoding='utf-8') f.write("1. keep working\n 2. do yourslef\n 3. to be NO.1\n 4. what are you 弄啥嘞 ") f.close()
# 文本读取
f = open("E:\Learning_2019\write_somthing.txt",mode= 'r',encoding='utf-8') print(f.read())
"""
1. keep working
2. do yourslef
3. to be NO.1
4. what are you 弄啥嘞
"""

Text reads:

f.read () to read all the contents of the text

f.readline () to read a line of text, from the first row

All rows f.readlines output list () to read the text

 

Guess you like

Origin www.cnblogs.com/wangxiaobei2019/p/11563172.html