当前位置:网站首页>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)
边栏推荐
猜你喜欢

JSP connecting Oracle to realize login and registration

Animation de ligne

Why is point shield cloud forced to quit playing?

How does the power outlet transmit electricity? Simple problems that have plagued my little friend for so many years
![[Verilog quick start of Niuke online question brushing series] ~ one out of four multiplexer](/img/1f/becda82f3136678c58dd8ed7bec8fe.png)
[Verilog quick start of Niuke online question brushing series] ~ one out of four multiplexer

Yin Yang master page

The heading angle of sliceplane is the same as that of math Corresponding transformation relation of atan2 (y, x)

MySQL 45讲 | 05 深入浅出索引(下)

Wedding studio portal applet based on wechat applet

Sqlmap tool user manual
随机推荐
msa. h: There is no such file or directory
Leecode question brushing-ii
WordPress zibll sub theme 6.4.1 happy version is free of authorization
电商转化率这么抽象,到底是个啥?
独立站卖家都在用的五大电子邮件营销技巧,你知道吗?
【JVM】——JVM中内存划分
Create NFS based storageclass on kubernetes
Study on modified triphosphate: lumiprobe amino-11-ddutp
数据仓库:DWS层设计原则
How to learn programmable logic controller (PLC)?
8VC Venture Cup 2017 - Elimination Round D. PolandBall and Polygon
JS中的链表(含leetcode例题)<持续更新~>
jq图片放大器
Camera Basics
Share a powerful tool for factor Mining: genetic programming
一看就会 MotionLayout使用的几种方式
Animation de ligne
Jdbc的使用
[JVM] - memory partition in JVM
It is the latest weapon to cross the blockade. It is one of the fastest ladders.