当前位置:网站首页>File, exception, module
File, exception, module
2022-07-20 11:45:00 【Ning Ranye】
Series articles :
List of articles
file
File read and write
file open
General format for file opening
with open(" File path ", " Turn on mode ", encoding= " Character encoding of operation file ") as f:
" Read and write the file accordingly "
Use with Benefits of block : After execution , Automatically update files close operation
- example 1 Read a simple file
with open("C:/Users/ytm/Desktop/ The test file .txt", "r", encoding="utf-8") as f: # The first step is to open the file
text = f.read() # Step 2 read the file
print(text)
1、 Turn on mode
“r” read only mode , If the file does not exist , Report errors
“w” Overwrite write mode , If the file does not exist , Create ; If the file exists , Then completely overwrite the original file
“x” Create write mode , If the file does not exist , Create ; If the file exists , Report errors
“a” Append write mode , If the file does not exist , Create ; If the file exists , Then add content after the original document
“b” Binary mode , Not to be used alone , It needs to be used together, such as "rb",“wb”,“ab”, This mode does not need to be specified encoding
“t” Text file mode , The default value is , To be used together Such as "rt",“wt”,“at”, Generally omit , Abbreviated as "r",“w”,“a”
“+”, And "r",“w”,“x”,"a" In combination with , Based on the original function , Add read and write function
Open mode default , The default is read-only mode
2、 File path
Absolute path or relative path
3、 Character encoding
- unicode utf-8 Contains characters needed in all countries of the world
- Chinese code gbk Specially solve the problem of Chinese coding .
windows Under the system , If the default , The default is gbk( Code of the region )
For the sake of clarity , In addition to dealing with binary files , It is recommended not to default encoding
File reading
1、 Read the whole content f.read()
with open("C:/Users/ytm/Desktop/ The test file .txt", "r", encoding="utf-8") as f: # The first step is to open the file
text = f.read() # Step 2 read the file
print(text)
Linjiang fairy · The Yangtze River flows east
The Yangtze River flows east , The waves wash away the heroes .
Right or wrong, turn around .
Green mountain is still in , Several sunsets are red .
White haired fisherman and woodcutter on the river , Used to watch the autumn moon and spring wind .
A pot of wine likes to meet .
How many things in ancient and modern times , All of them are laughing .
Decoding mode does not match
with open("C:/Users/ytm/Desktop/ The test file .txt", "r" ) as f: # encoding default windows The system defaults to gbk
text = f.read() # Step 2 read the file
print(text)
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 50: illegal multibyte sequence
2、 Read line by line - f.readline()
with open("C:/Users/ytm/Desktop/ The test file .txt", "r", encoding="utf-8" ) as f: # encoding default windows The system defaults to gbk
for i in range(3):
text = f.readline()
print(text)
Linjiang fairy · The Yangtze River flows east
The Yangtze River flows east , The waves wash away the heroes .
Right or wrong, turn around .
with open("C:/Users/ytm/Desktop/ The test file .txt", "r", encoding="utf-8" ) as f: # encoding default windows The system defaults to gbk
while True:
text = f.readline()
if not text:
break
else:
print(text, end="") ## Keep the newline of the original , send print() Line feed of does not work
Linjiang fairy · The Yangtze River flows east
The Yangtze River flows east , The waves wash away the heroes .
Right or wrong, turn around .
Green mountain is still in , Several sunsets are red .
White haired fisherman and woodcutter on the river , Used to watch the autumn moon and spring wind .
A pot of wine likes to meet .
How many things in ancient and modern times , All of them are laughing .
3、 Read in all lines , Form a list with each behavior element f.readlines()
with open("C:/Users/ytm/Desktop/ The test file .txt", "r", encoding="utf-8" ) as f: # encoding default windows The system defaults to gbk
text = f.readlines()
print(text)
[' Linjiang fairy · The Yangtze River flows east \n', ' The Yangtze River flows east , The waves wash away the heroes .\n', ' Right or wrong, turn around .\n', ' Green mountain is still in , Several sunsets are red .\n', ' White haired fisherman and woodcutter on the river , Used to watch the autumn moon and spring wind .\n', ' A pot of wine likes to meet .\n', ' How many things in ancient and modern times , All of them are laughing .']
with open("C:/Users/ytm/Desktop/ The test file .txt", "r", encoding="utf-8" ) as f: # encoding default windows The system defaults to gbk
for text in f.readlines():
print(text,end="")
Linjiang fairy · The Yangtze River flows east
The Yangtze River flows east , The waves wash away the heroes .
Right or wrong, turn around .
Green mountain is still in , Several sunsets are red .
White haired fisherman and woodcutter on the river , Used to watch the autumn moon and spring wind .
A pot of wine likes to meet .
How many things in ancient and modern times , All of them are laughing .
4、 Text file reading summary
When the file is large ,read() and readlines() Too much memory , Not recommended
readline It's not convenient to use
5、 Binary
with open("test.jpg", "rb") as f:
print(len(f.readlines()))
File is written to
1、 Write a string or byte stream to the file ( Binary system )f.write()
with open(" Love songs 1980.txt", "w", encoding="utf-8") as f:
f.write(" You once said to me \n") # If the file does not exist, create one immediately
f.write(" You always love me \n") # If the file exists , It will cover !!!
f.write(" I understand love \n")
f.write(" But what is forever \n") # If you need a new line , Final newline \n
2、 Append mode ——“a”
3、 Write a list whose element is a string to the file as a whole ——f.writelines()
ls = [" The wind blows in spring ", " It rains in autumn ", " How many vows of eternal love go with the wind in spring and autumn "]
with open("C:/Users/ytm/Desktop/ The test file .txt", "w", encoding="utf-8" ) as f: # encoding default windows The system defaults to gbk
f.writelines(ls)
exception handling
Common exceptions occur
- except 0 operation ZeroDivisionError
- Cannot find readable file FileNotFoundError
- Wrong value ValueError
Pass in a value that the caller doesn't expect , Even if the type of the value is correct
s = “1.3”
n = int(s) - Index error IndexError
The subscript crossing the line - Type error TypeError
NameError Use an undefined variable
KeyError Trying to access a key that doesn't exist in the dictionary
When an exception occurs , If the processing method is not preset , The program will break
exception handling
try_except
- If try The inner code block executes smoothly ,except Not triggered
- If try An error occurred in the inner code block , Trigger except, perform except Internal code block
- Omnipotent abnormality Exception ( All the wrong ancestors )
- Catch the abnormal value as
- If try Module execution , be else The module also performs ry_except_else
- Can be else regard as try The bonus of success
- Regardless of try Whether the module performs ,finally At the end of the day try_except_finally
x = 10
y = 0
ls = []
d = {
"name":" Big hero "}
try:
z = x/y
except ZeroDivisionError:
print("0 Not divisible !!!")
except NameError:
print(" Variable name does not exist ")
except KeyError:
print(" The key doesn't exist ")
except Exception as e: # Omnipotent abnormality Exception ( All the wrong ancestors )
print(" Error !")
print(e) # Capture exception
else:
print("else regard as try The bonus of success ")
finally:
print(" Whether touching or not triggers an exception , Will execute ")
modular
Has been encapsulated , No need to “ To build the wheels ”, Declare after import , Use immediately
Generalized module classification
- Python built-in
Time bank time Random library random Container data type collection iterator function itertools - Third party Library
Data analysis numpy 、pandas Data visualization matplotlib machine learning scikit-learn Deep learning Tensorflow - Customization files
A separate py file
package ---- Multiple py file
Module import
- Import the entire module ----- import Module name
import time
start = time.time()
time.sleep(3)
end = time.time()
print(" Program running time :{}".format(end-start))
import fun1
fun1.f1()
- Import a class or function from a module ---- from modular import Class name or function name
from itertools import product
ls = list(product("AB","123"))
print(ls)
[('A', '1'), ('A', '2'), ('A', '3'), ('B', '1'), ('B', '2'), ('B', '3')]
from function.fun1 import f1 # Pay attention to this usage
f1()
Import more than one at a time
from function import fun1, fun2
fun1.f1()
fun2.f2()
- Import all classes and functions in the module —from modular import *
from random import *
print(randint(1,100)) # Produce a [1,100] Random integer between
print(random()) # Produce a [0,1) Between random decimals
Module lookup path
Module search order :
- Priority is given to importing modules from memory
- Built-in module
# Python Startup time , The interpreter will load some by default modules Store in sys.modules in
# sys.modules The variable contains one loaded by the current ( Complete and successful import ) A dictionary of modules to the interpreter , Module name as key , Their positions are taken as values
import math
import sys
# print(sys.modules)
print("math" in sys.modules) #True
print("numpy" in sys.modules) #False
sys.path Modules contained in path
import sys
print(sys.path)
- sys.path The first path of is the folder where the current execution file is located
- If you need to import modules that are not in this folder , You need to add the path of the module to sys.path
import sys
sys.path.append("C:\\Users\\ibm\\Desktop") # Notice the double slash
import fun3
fun3.f3()
边栏推荐
- 2022 Shandong Province safety officer C certificate operation certificate examination questions and answers
- ERP能力计划与排产
- OSError: exception: access violation writing 0x0000000000000000
- yum install 报警 No package xxxx available
- IPv6-ICMPv6协议
- LabVIEW在同一个面板下描绘模拟波形和数字波形
- leetcode-11 盛水最多的容器(双指针,lower_bound, upperbound)
- C essentialism generic
- 虚拟展会结合AI数字人,帮助企业解决当下困局
- 《论文复现》BiDAF代码实现过程(1)数据处理
猜你喜欢
《实现细节》字符索引向字词索引的转化代码
为什么把 360bookmarks拷到新电脑上无法恢复收藏夹,因为 他是加密的 您可以使用360sefav_日期.favdb和360default_ori_日期.favdb两种收藏夹备份文件导入浏览器
快解析如何与私有化部署结合
Wechat applet bindinput and click the button to assign the content of the current text
【NightCafe AI】一分钟创建你想要的NFT数字艺术藏品
分页数据的处理
Day 5 notes sorting
Processing of paging data
Convolutional neural network model -- vgg-16 network structure and code implementation
20220710 leetcode周赛:移动片段得到字符串
随机推荐
爬虫初级知识点(1)
快解析远程服务,助力企业实现高效客户维护
多层感知机如何调超参数
TortoiseSVN Error : Previous operation has not finished; run ‘cleanup‘ if it was interrupted异常解决办法
【NightCafe AI】一分钟创建你想要的NFT数字艺术藏品
神经网络模型如何应用到实际 - 神经网络模型数学建模案例
关于近期《DEJA_VU3D功能集》专栏未更新说明专栏未更新说明
快解析如何与私有化部署结合
golang 回调函数 & 闭包
软件开发设计流程
ES6新增(一)let与常量
(图解)FPN的来龙去脉
2022年山东省安全员C证操作证考试题及答案
已解决(selenium报错)AttributeError: ‘WebDriver‘ object has no attribute ‘execute_cdp_cmd‘
神经网络模型的描述 - 简单的神经网络模型
Application of split slip ring in motor
Towhee 每日模型周报
软件测试—学习笔记4
对象的比较
文件上传漏洞(一)