Basic operation of the file
The main point here is how to open the file, set the file open permissions and the way
Open File
The mode of opening the file is:
- R, read-only mode (default).
- W, write-only mode. "unreadable; not exist; create; delete content;"
- A, append mode. "Readable; not exist" create; "only append content;"
"+" means you can read and write a file at the same time
- r+, can read and write files. "readable; writable; can be added"
- w+, write and read
- A +, with a
"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading
"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)
The opening syntax of a file is generally an open () statement
1 F = open ("txt","R"# To open a file named txt f variable as a file with read-only Operation object 23#
Note When you open a file with read-only ' R ', the content is read from the beginning of the file header. When you open a file with append ' A ', the content is written from the end of the file. When writing a file to a file using write-only ' W ', a new file is created to write the content to the new file and overwrite the old file so that the contents of the original file disappear.
Practice
Writing the Login interface
- Enter User name password
- Show welcome message after successful authentication
- Three-time error after locking
List of locked users
Dick and Harry
Lockedname
List of logged-in users
Nicholas Zhao 4,123456
Login
1 #Auther:xiaoliuer Li2 3 ImportSYS4 5f = open ("Lockedname","R", encoding="Utf-8")#open a locked user list read files from the beginning6F1 = open ("Login","R", encoding="Utf-8")#Open the list of logged-in users7 8 9 Ten Onei = 0#set a variable to control the number of loops A whileI < 3: - -user = input ("Please enter user name:") the forLineinchF:#search for usernames on locked lists - ifuser = =Line.strip (): - Print("user%s has been locked"%user) -Sys.exit ()#jump out of the program + - ifLen (user) = =0: + Print("user name cannot be empty please re-enter") A Continue at -passwd = input ("Please enter your password:") -T = False#set a variable to jump out of a loop - forLineinchF1: - ifLine.split () [0] = = User andLine.split () [1] = =passwd: - Print("success!") inT =True - Break to + ifT = = False:#Enter this loop when the variable is an input user and password error, and increase the number of times from one time - ifI < 2: the Print('your user or password is wrong, please re-enter! ') *i + = 1 $ Panax Notoginseng Else: - Print("Welcome user%s to login system"%user) the Break + A Else: thef = open ("Lockedname","a", encoding="Utf-8")#Append user name to end of file + Print("Your user%s has been locked! "%user)#write the three wrong username into the list -F.write ("\ n"+user) $ $ - f.close () -F1.close ()
How to open a file gracefully