当前位置:网站首页>File foundation - read / write, storage
File foundation - read / write, storage
2022-06-28 05:31:00 【Naive code writing】
Document basis :
Common codes :
ASCLL Encoding table : common 0 yes 48;A yes 65;a yes 97
• 8 Bit binary represents a character
• Capable of representing letters 、 Numbers etc.
UTF-8 Can compile Chinese
Python Common library :
- os A large number of operation files are provided 、 Directory method .
- pathlib2 File system path operation
- openpyxl operation Excel file .
- python-docx operation Word file .
- python-pptx operation PowerPoint file .
- opencv-python Image processing module , It provides powerful image processing related functions .
Open file :
Open a file , And return the file object , In the process of file processing, you need to use the operation after opening the file
open(file, mode=‘r’) #mode= Write but not write
Use open() Methods must ensure that the file object is closed , That is to call close() Method
file: It's necessary , File path ( Relative or absolute paths )“ file name ”.
mode: Optional , File open mode .
- ‘r’ Reading documents (read)
- ‘w’ Writing documents (write)
- ‘a’ Append content at the end of the file (append)
- ‘b’ Binary ( image file 、binary)
- ‘t’ text file (text)
- '+' Reunite with (r+: Reading and writing 、 Write from scratch ;w+: Reading and writing 、 Read / write after emptying the source file )
Close file :
Use open() Methods must ensure that the file object is closed , That is to call close() Method .
file.close()
But use with ….as…., Implicit call close() Method to close the file
with open(‘file.txt’, ‘r’) as f:
Close file . After closing, the file can no longer be read or written . No input close
File attribute :
- file.name: Return the name of the file ;
- file.mode: Return to open file , File open mode adopted ;
- file.encoding: Returns the encoding format used to open the file ;
- file.closed: Judge whether the document has been closed .
practice :
f=open("lzs.txt",'r')
print(f.closed) # Check whether the file is closed , It is not closed at this time , Returns the Flase
f.close()# Open before, close now
print(f.closed)# It will return to True
with open("lzs.txt",'r')as f: # Open with this
print(f.closed) # At this time, judge whether to close , return Flase; It should be in the file
print(f.closed)# Now outside the file , return True
with open("lzs.txt",'r',encoding="utf-8")as f: # The document is in Chinese , To change the coding table , use encoding
x=f.readlines()
for i in x:
print(i,end="")
Read the file :
function read(): A separate read Errors will be displayed if there are Chinese characters or Chinese symbols in the reading , The reason is that the codes are different , So add... Later encoding="utf-8”, Transcoding can output Chinese .
Read the contents of the file byte by byte or character by character , When there are parameters , Read parameter bytes or characters ;
with open("lzs2.txt",'r')as f:
x=f.read() # Self understanding : Read byte , character , Numbers ;(6) The number in the middle represents how many ,6 The delegate reads 6 individual
print(x,end=" ")# Price end=" " The reason is that there will be a blank line after the function output , It can be used end=" " To delete .
with open("lzs.txt",'r',encoding="utf-8")as f: # This file is in Chinese , It can be output , The document is in Chinese , To change the coding table , use encoding
x=f.readlines()
for i in x:
print(i,end="")
function readline():
with open("lzs2.txt",'r')as f:
x=f.readline()# Read the lines in the file ;() The number in represents several numbers in the read line , When you enter a number , There is no blank line at the end , But the input number is not greater than the read size
print(x.strip()) #.strip effect : Put the last '\n' Delete and end="" equally , The two methods .
function readlines(): Read multiple lines of the file at once ,
x=f.readlines() # What is read out is a list
with open("lzs2.txt",'r')as f:
x=f.readlines() # here x It's a list
for i in x: # It can be traversed ( Cyclic output ) it
print(i,end="")
Output results :
12324543645247
1243253543
2143325
1312233421
43154
Format control :
Format control can be performed during reading ;
Read the file (lzs2.txt) The content of
from datetime import datetime The import module
x="lzs2.txt"
with open("lzs2.txt",'r') as f:
for i in f.readlines():
mydate,price = i.split(',')# Define assignment variables use split With , Separate
# print(mydate,end=" ")
# print(price)
dt=datetime.strptime(mydate,"%Y/%m/%d") #strptime() Function parses a time string into a time tuple according to the specified format
# print(dt)
price=float(price) # There will be price Convert to floating point number , For appearance, there is a decimal point , Whether you actually turn it or not , because price The assigned value is the number
# print( dt,end=" ")
# print(price)
print(" Time is :",str(dt.date())," sales :",str(price))# Use here str Conversion because I converted , If it was not a string or a number , You need to turn
Output results :
Time is : 2021-06-02 sales : 1567.0
Time is : 2021-06-03 sales : 1244.0
Time is : 2021-06-04 sales : 4353.0
Time is : 2021-06-05 sales : 1324.0
Storage file :
function write():
Write a character or a byte string
f.write(‘hello,world’)
x="lzs3.txt"
with open(x,'w',encoding="utf-8") as f: # If not before x This file , This step will directly generate a new file ,w Is write function
f.write(" This year will be a great year , Make a lot of money , Sure !!") # Writing Chinese is not supported , There must be a step of code conversion ahead
y="lzs4.txt"
with open(y,mode='r+',encoding="utf-8") as f:#r+ It's reading and writing , Overwrite from the original file ,w+ Is to empty the original file , Write from the beginning .
f.write(" The family must be safe and happy !!!")
function writelines( )
Used to write... To a file A sequence String or byte string of , A sequence can be a list 、 Tuples 、 Dictionaries 、 Collection etc. ;
writelines()
x=open("lzs.txt","r",encoding="utf-8")
y=open("./ New folder / new .txt","w",encoding="utf-8")
y.writelines(x.readlines())# hold x Copy content from to y Inside , because y The original file already exists, so the y Directly replace the file in
# therefore y Generally, it is an empty file , Or create a new file directly
x.close()
y.close()# use open It must be opened with close shut;turn off
Format control :
from datetime import datetime
file = "file2.txt"
with open(file, 'w') as f:
dt = datetime.strptime("2020/6/25", '%Y/%m/%d') # Format and output the data
result=str(dt.date()) #
f.write(result)
边栏推荐
- What is the difference between AC and DC?
- Informatics Orsay all in one 1360: strange lift
- Online yaml to JSON tool
- Docker安装Mysql5.7并开启binlog
- V4L2 驱动层分析
- When using the MessageBox of class toplevel, a problem pops up in the window.
- Programmer - Shepherd
- 刘海屏手机在部分页面通过[[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom得到底部安全区高度为0问题
- 小球弹弹乐
- 指定默认参数值 仍报错:error: the following arguments are required:
猜你喜欢
电子邮件营销的优势在哪里?为什么shopline独立站卖家如此重视?
Detailed usage configuration of the shutter textbutton, overview of the shutter buttonstyle style and Practice
Docker installs mysql5.7 and starts binlog
RL 实践(0)—— 及第平台辛丑年冬赛季【Rule-based policy】
Create NFS based storageclass on kubernetes
Reactive dye research: lumiprobe af594 NHS ester, 5-isomer
Docker安装Mysql5.7并开启binlog
Amino dye research: lumiprobe fam amine, 6-isomer
中小型水库大坝安全自动监测系统解决方案
【C语言练习——打印空心正方形及其变形】
随机推荐
V4L2 驱动层分析
jq图片放大器
数据中台:六问数据中台
Deeplearning ai-week1-quiz
If a programmer goes to prison, will he be assigned to write code?
MySQL 45讲 | 05 深入浅出索引(下)
中小型水库大坝安全自动监测系统解决方案
[C language practice - printing hollow square and its deformation]
When excel copies the contents of a row, the columns are separated by the tab "\t"
CpG solid support research: lumiprobe general CpG type II
How high is the gold content of grade II cost engineer certificate? Just look at this
Concurrent wait/notify description
北斗三号短报文终端在大坝安全监测方案的应用
Enum
MySQL export query results to excel file
Carboxylic acid study: lumiprobe sulfoacyanine 7 dicarboxylic acid
Docker installs mysql5.7 and starts binlog
Hundreds of lines of code to implement a script interpreter
mysql 导出查询结果成 excel 文件
数据中台:数据治理的建设思路以及落地经验