File Handling
What is document processing
Modify the stored information
What is the file
The concept of virtual storage of information provided by the OS (binary to store information)
open a file
f = open(r'文件路径','打开模式',encoding='某种编码')
Modify the file
f.write()
save document
f.flush()
Close the file
f.close()
Three file open mode
r: read mode
f.read () # read all text
f.readline () # read line by line
w: Clear writing mode
f.write()
a: additional writing
f.write
encoding format specified encoding / writing the read file
Open the file in two ways
t: Text
Class files for text
and r / w / a conjunction, do not add encoding
d: Binary
Audio files for
the r / w / a conjunction, do not add encoding
file path
Absolute path
From the beginning of the letter D: \ ss \ ss \ ss.txt
relative path
And execute files belong to the same folder (writing project as much as possible relative path)
with file management context
whit provides an automatic function closes the file, lifting the occupancy of the operating system.
with open('文件路径','打开模式',encoding='编码格式') as f:
pass
Advanced application file
r +: readable and writable, writing overlay
w +: read-write, clear write
a +: readable and writable, after the default cursor, the cursor can not be read after the data
Cursor movement
== == English one byte characters, Chinese == == a three-byte characters
seek
seek (n) # n bytes moved, default scratch
whence
Only a predetermined (0,1,2) three modes, a header begins with 0, 1 is the start location of the files, the file 2 starts tail
tell
Tell your current location
truncate
truncate (n) #n reserved for the few on the top few
read
Move the cursor to the character as a unit, n is the number of characters, do not write all the default.
registered
count = 0
while count < 3:
uname = input('输入名字:')
upwd = input('输入密码:')
upwd_inp = input('再次输入密码:')
if not upwd == upwd_inp:
print('俩次密码不一致')
count += 1
continue
with open(r'jsb.txt','a',encoding='utf8')as fa:
fa.write(f'{uname}:{upwd}\n')
fa.flush()
break
Sign in
uname = input('输入名字:')
upwd = input('输入密码:')
with open(r'jsb.txt','r',encoding='utf8')as fr:
for jsb in fr:
name,pwd = jsb.split(':')
if name.strip() == uname and pwd.strip == upwd :
print('登入成功')
break
else:
print('登入失败')
File modification
Do not modify a file that only coverage.