- File operation related
The two most commonly used methods of 01open and 02csv
01 open function operation file
file write
with open('./data.txt',mode='a',encoding='utf8') as f:
# file write
f.write("helloworld123\n")
f.writelines(['xiaoming\n','xiaowang\n'])
f.write('Zhang San and Li Si')
file read
with open('./data.txt',mode='r',encoding='utf8') as f:
# read all contents of the file
# lines = f.read()
# print(lines)
lines = f.readlines() # return list data
print(lines)
02 Reading and writing of csv files
The reader and writer classes in the Csv module can be used to read and write serialized data
write to file
import csv
with open('./data.csv',mode='w',newline='',encoding='utf8') as file: #This is a file opened
# write file class
fw = csv.writer(file) #write to file, use writer
fw.writerow(["abcdefgh",'username'] ) #abcdefgh is the written sequence
fw.writerow(['helloworld','xiaoming'])
# After running, two rows of data will be generated
fw.writerows([('hahaha','wawawa'),('xiaoming','xiaowang')])
#Writerows is to pass in multiple data
read file
import csv
with open('./data.csv',mode='r',newline='',encoding='utf8') as file:
cr = csv.reader(file)
for line in cr:
print(line)
There are quite a lot of methods, and you can use them commonly
- python exception handling
Abnormal events will occur during program execution, affecting the normal execution of the program.
Normally, an exception occurs when Python cannot handle a program normally.
When an exception occurs in the Python script, we need to catch and handle it, otherwise the program will terminate execution.
Exception handling:
1. try/except statement
The try/except statement is used to detect errors in the try statement block, and let the except statement capture and process exception information.
If you don't want to end the program when an exception occurs, just catch it in try.
The syntax of try....except...else :
try:
<statement> # run other code
except <name> :
<statement> #If a 'name' exception is raised in the try part
except <name>, <data>:
<statement> # If a 'name' exception is raised, get additional data
else:
<statement> #if no exception occurs
The working principle of #try is that when a try statement is started, python marks the context of the current program, so that when an exception occurs, it can return here, the try clause is executed first, and what happens next depends on the execution whether an exception occurs.
- If an exception occurs when the statement after the try is executed, python jumps back to the try and executes the first except clause that matches the exception. exception).
- If an exception occurs in the statement after try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (this will end the program and print the default error message).
- If no exception occurs during the execution of the try clause, python will execute the statement after the else statement (if there is an else), and then control flow through the entire try statement.
Use except without any exception type
Use except without any exception type, as follows:
try:
normal operation
......................except:
An exception occurs, execute this code
......................else:
If there is no exception, execute this code
Use except with multiple exception types
Use the same except statement to handle multiple exception information, as follows:
try:
normal operation
......................except(Exception1[, Exception2[,...ExceptionN]]]):
One of the above exceptions occurs, execute this code
......................else:
If there is no exception, execute this code
2. try-finally statement
The try-finally statement executes the final code whether or not an exception occurs.
try:
<statement>
finally:
<statement> # always execute when exiting try
raise
3. Abnormal parameters
An exception can take parameters, which can be used as output exception information parameters.
Use the except statement to capture the exception parameters, as follows:
try:
normal operation
......................except ExceptionType, Argument:
You can output the value of Argument here ...
The exception value received by the variable is usually contained in the exception's statement. Variables in the form of tuples can receive one or more values.
The tuple usually contains error string, error number, error location.
4. Trigger an exception
You can use the raise statement to trigger exceptions yourself
The syntax format of raise is as follows:
raise [Exception [, args [, traceback]]]
In the statement, Exception is any of the standard exceptions of the type of exception (for example, NameError), and args is the exception parameter provided by itself.
The last parameter is optional (rarely used), and if present, is the trace exception object.
5. User-defined exceptions
By creating a new exception class, programs can name their own exceptions. Exceptions should typically inherit from the Exception class, either directly or indirectly.
The following is an example related to RuntimeError. A class is created in the example, and the base class is RuntimeError, which is used to output more information when an exception is triggered.
In the try statement block, the except block statement is executed after the user-defined exception, and the variable e is used to create an instance of the Networkerror class.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
After the above class is defined, the exception can be triggered as follows:
try:
raise Networkerror("Bad hostname")except Networkerror,e:
print e.args
If you don't understand, practice more
Video: Python file processing topic
Up:ABTester
https://www.yuque.com/imhelloworld/alzshs/zywwlo ( alternate