read txt text

python There are three common file reading functions read(),readline(),readlines() 
 
To read the above txt take as an example , Look at the difference

read()    Read all at once

Read all the contents of the text at once , Returns the result as a string
with open("test.txt", "r") as f: # Open the file data = f.read() # read file print(data)

readline()    Read the first line

Read only the first line of text , Returns the result as a string
with open("test.txt", "r") as f: data = f.readline() print(data)

readlines()      list

Read all contents of text , And returns the result in the form of a sequence , General coordination for in use
with open("test.txt", "r") as f: data = f.readlines() print(data)

readlines You'll read line breaks , It can be removed as follows :
with open("test.txt", "r") as f: for line in f.readlines(): line =
line.strip('\n') # Remove the line breaks for each element in the list print(line)

 

write in txt text
with open("test.txt","w") as f: f.write(" This is a test !") # With file closing function , No need to write it again f.close()
 

read-write mode

To understand the file read-write mode , You need to understand the differences between several models , And the corresponding pointer

r :    read file , If the file does not exist, an error will be reported

w:    write file , If the file does not exist, it is created and then written , The original file will be overwritten

a :    write file , If the file does not exist, it is created and then written , But the original file will not be overwritten , It is appended to the end of the file

rb,wb:  On r,w similar , But for reading and writing binary files

r+ :    readable , Writable , If the file does not exist, an error will be reported , Will be overridden during write operation

w+ :    readable , Writable , The file does not exist. Create it first , Will be covered

a+ :  readable , Writable , The file does not exist. Create it first , Will not be covered , Append at the end

Technology
©2019-2020 Toolsou All rights reserved,
Huawei 2021 session Hardware Engineer Logical post (FPGA) Super detailed surface !!!Vue-element-admin upgrade ui edition virtual machine VMware Download and install the most detailed tutorial !C++ Move constructor and copy constructor sound of dripping water java Backstage interview pygame Realize full screen mode and adjustable window size mysql Database setting character set configuration modification my.ini file (windows)30 What's the experience of being a junior programmer at the age of 20 C++ Multithreading programming ( Summary of common functions and parameters )python_ cherry tree