python foundation 6: files
1, File operation
1. [know] the role of documents
- The role of files: persistent storage of data
2. [key] basic operation of documents
- Document operation process
- Open a file or create a new one
- Read / write data
- Close file
- Open file: file variable = open("file name", "access mode")
- Closing files: file variables close()
"""Process of operating documents: 1. Open file 2. Read or write files 3. Close file """ # Open file format # Note: the file name and opening permission are in string format # File variable = open (file name, access mode) # 'w': open the file in write only mode, the file does not exist, create the file, and empty the file content f = open("xxx.txt", "w") # Close the file in order to free up resources # File variables close() f.close()
2.1. [memory] the file closes automatically
-
Format:
-
with open("file name", "Access mode") as File variable name: pass # File operation: when the file operation ends, the file will be closed automatically
-
-
# As long as the file is open, run the with statement and close the file automatically # with open() as file variable alias: # File operation with open("abc.txt", "w") as f: # File operation. After executing the code block, the file will be closed automatically pass
3. [key] file writing
-
Format:
File variable.write("What needs to be written")
""" # 1. Open the file in write only mode # 2. Write documents # 3. Close the file """ # 1. Open the file in write only mode f = open("xxx.txt", "w") # 2. Write documents # Write file format: file variable Write (required content) f.write("hello abc") f.write(" hello python\n") f.write(" hello tom") # 3. Close the file f.close()
4. [key] file reading
4.1. read specifies what to read:
-
Read content = file variable Read (read / write character length), n is the number of characters read. If it is not set, all characters will be read
-
# 1. Open the file in read-only mode, 'r' # 2. Read file contents # 3. Close the file # 1. Open the file in read-only mode, 'r' # 'r': to open a file, it must exist. If it does not exist, an error is reported and the file crashes f = open("xxx.txt", "r") # 2. Read file contents # Format: content variable = file variable Read (read character length) # If the length of read is not specified, all are read by default ret = f.read(4) print(ret) ret = f.read(7) print(ret) ret = f.read() print(ret) # 3. Close the file f.close()
Extension: encoding = "encoding method"
# 1. Open the file in read-only mode, 'r' # 2. Read file contents # 3. Close the file # 1. Open the file in read-only mode, 'r' # 'r': to open a file, it must exist. If it does not exist, an error is reported and the file crashes # f = open("xxx.txt", "r") # By default, python of windows uses open to open the file GBK (national standard simplified and traditional Chinese code) f = open("xxx.txt", "r", encoding="utf-8") # Encoding uses keywords to pass parameters. You can specify the encoding method of the open file and use UTF-8 (International encoding) # f.write("hello") # io.UnsupportedOperation: not writable # 2. Read file contents # Format: content variable = file variable Read (read length) # If the length of read is not specified, all are read by default ret = f.read(4) # 4: 4 words, including the number of Chinese words print(ret) ret = f.read(7) print(ret) ret = f.read() print(ret) # 3. Close the file f.close()
4.2. readlines read all lines:
-
Content list variable = file variable readlines()
-
# 1. Open the file in read-only mode, 'r' # 2. Read file contents # 3. Close the file # 1. Open the file in read-only mode, 'r' # 'r': to open a file, it must exist. If it does not exist, an error is reported and the file crashes f = open("xxx.txt", "r", encoding="utf-8") # 2. Read file contents # readlines: read all rows, and use the row as the separation condition # Format: content list variable = file variable readlines() r_list = f.readlines() print(r_list) # ['Hello, Zhang San \ n', 'hello abc\n', 'hello python\n', 'hello tom\n', 'hello rose\n', 'hello mike'] # Fetch all elements of the list through for for row in r_list: # print(row) print(row, end="") # print output without line breaks # 3. Close the file f.close()
4.3. readline reads one line at a time:
-
Content variable = file variable readline()
-
# 1. Open the file in read-only mode, 'r' # 2. Read file contents # 3. Close the file # 1. Open the file in read-only mode, 'r' # 'r': to open a file, it must exist. If it does not exist, an error is reported and the file crashes f = open("xxx.txt", "r", encoding="utf-8") # 2. Read file contents # readlines: read all lines # readline: read one line at a time # ReadLine format: content variable = file variable readline() # ret = f.readline() # print(ret) # # ret = f.readline() # print(ret) # # ret = f.readline() # print(ret) while True: ret = f.readline() # if ret == "": # "" indicates false if not ret: # not false -- > true break print(ret) # 3. Close the file f.close()
5. [memory] open the file for detailed explanation
5.1 difference between [memory] access modes R, W and a
-
Open the file in read-only mode, the file does not exist, and an error is reported
-
# File open access mode # File variable = open (file name, access mode) # 'r', open the file in read-only mode, the file does not exist, and an error is reported # Note 1: the default opening method of open is "r" # f = open("abc.txt") # Note 2: "r": if the file does not exist, an error will be reported # f = open("abc.txt", "r") # FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
f = open("abc.txt", "r")
Note 3: "r": open the file read-only and cannot be written
f.write("hello world") # io.UnsupportedOperation: not writable
ret = f.read()
print(ret)
f.close()
- Open the file in write only mode, the file does not exist, create a new file, and empty the file content - ```python # File open access mode # File variable = open (file name, access mode) # 'w', open the file in write only mode, the file does not exist, create a new file, and empty the contents of the file # 1. The new file does not exist # 2. If the file exists, empty the contents of the file f = open("abc.txt", "w") # 3."w": write only, open, not read # ret = f.read() # io.UnsupportedOperation: not readable f.close()
- When the file is opened in the append mode, there is no new file, the write cursor is placed at the end of the file, and the write data is directly written at the end of the file
-
# The file is opened in the append mode. The file does not exist. The new file exists. The write cursor is placed at the end of the file, and the write data is directly written at the end of the file # 1. 'a', open the file by appending # 1) New file does not exist # 2) The file exists and the write cursor is placed at the end of the file f = open("abc.txt", "a") # 3) "a": cannot read f.read() # io.UnsupportedOperation: not readable # 2. Write data f.write("hello python") # 3. Close the file f.close()
5.2 [memory] the difference between absolute path and relative path
-
Absolute path: refers to the path where the file really exists on the hard disk. It is the complete path of the computer
-
# 1. Open the file under the absolute path. If the absolute path E:/Code/PyCode does not exist, the opening fails # print("\\") # In the string, \ represents escape character, \ n: line feed \ t: tab key,.... \ \:\ character # print("C:\\Users\\35477\\Desktop\\python40\\day06\\"+"abc.txt") # Absolute path: the full path of the file in the disk, calculated from the drive letter # f = open("C:\\Users\\35477\\Desktop\\python40\\day06\\"+"abc.txt", "r") f = open("C:/Users/35477/Desktop/python40/day06/"+"abc.txt", "r")
ret = f.read()
print(ret)
f.close()
- Relative path: relative to your target file location - `1.txt`: Equivalent to`./1.txt`,Under the current path`1.txt` - `../1.txt`: Under the upper path`1.txt` ```python # 2. Open the file under the relative path. Relative to the current target file, it is the path where the current py file is located # 2.1 under the current path, if the file does not exist, create a new file # f = open("abc.txt", "r") f = open("./abc.txt", "r") # . / indicates the current path ret = f.read() print(ret) f.close() # 2.2 if the file does not exist under the upper path, create a new file f = open("../abc.txt", "w") # .. / indicates the upper level path of the current path f.close()
6. [application] file backup case
-
Implementation idea:
1. Open source file read-only(Old file) 2. Open a new backup file in write only mode(new file) 3. while True: 4. Read the contents of the source file one point at a time 5. If the content is read, write it to the write file 6. If the content is not read, the file has been read, break Jump out of loop 7. Close file
- Normal version:
""" # 1. Open the source file ABC in read-only mode txt # 2. Open a new backup file abc [backup] in write only mode txt # 3. Read the contents of the source file at one time (read) # 4. Write the read content into the write file # 5. Close the file # Note: reading the contents of the source file at one time requires a lot of memory overhead, which may cause insufficient memory and cannot be copied """ # 1. Open the source file ABC in read-only mode txt f_src = open("abc.txt", "r") # 2. Open a new backup file abc [backup] in write only mode txt f_dest = open("abc[backups].txt", "w") # 3. Read the contents of the source file at one time (read) data = f_src.read() # 4. Write the read content into the write file f_dest.write(data) # 5. Close the file f_src.close() f_dest.close()
- Slice reading
""" # 1. Open source file (old file) in read-only mode # 2. Open a new backup file (new file) in write only mode # 3. while True: # 4. Read the contents of the source file one point at a time # 5. If the content is read, write it into the write file # 6. If the content is not read, the file has been read, and break jumps out of the loop # 7. Close the file # Note: read the contents of the source file a little at a time to save memory overhead """ # 1. Open source file (old file) in read-only mode old_file = open("abc.txt", "r") # 2. Open a new backup file (new file) in write only mode new_file = open("abc[backups].txt", "w") # 3. while True: while True: # 4. Read the contents of the source file one point at a time (1024 characters at a time) ret = old_file.read(1024) # 5. If the content is read, write it into the write file new_file.write(ret) # 6. If the content is not read, the file has been read, and break jumps out of the loop # '': a string with space characters # '': empty string if ret == "": # if not ret: break # 7. Close the file old_file.close() new_file.close()
- Get backup file name
# The copied file name should not be written dead. The user needs to input # The name of the new file becomes: old file name [backup] txt # 1. String search The position of rfind, r is right, look from right to left file_name = "a.b.c.txt" pos = file_name.rfind(".") # print(pos) # 2. Extract the desired string by slicing l_file_name = file_name[:pos] r_file_name = file_name[pos:] # print(l_file_name) # print(r_file_name) new_file_name = l_file_name + '[backups]' + r_file_name print(new_file_name)
- Modify the copy version of the file name
# The copied file name should not be written dead. The user needs to input # The name of the new file becomes: old file name [copy] txt """ # a. Enter the file name old to be copied_ file_ name = input() # b. Find the first point on the right of the file name and assemble it through slicing: old file name [backup] suffix # 1. Open source file (old file) in read-only mode # 2. Open a new backup file (new file) in write only mode # 3. while True: # 4. Read the contents of the source file one point at a time # 5. If the content is read, write it into the write file # 6. If the content is not read, the file has been read, and break jumps out of the loop # 7. Close the file """ # a. Enter the file name old to be copied_ file_ name = input() old_file_name = input("Enter the file name to be copied: ") # b. Find the first point on the right of the file name and assemble it through slicing: old file name [backup] suffix pos = old_file_name.rfind(".") l_file_name = old_file_name[:pos] r_file_name = old_file_name[pos:] new_file_name = l_file_name + "[backups]" + r_file_name # 1. Open source file (old file) in read-only mode old_file = open(old_file_name, "r") # 2. Open a new backup file (new file) in write only mode new_file = open(new_file_name, "w") # 3. while True: while True: # 4. Read the contents of the source file one point at a time ret = old_file.read(1024) # 5. If the content is read, write it into the write file new_file.write(ret) # 6. If the content is not read, the file has been read, and break jumps out of the loop if ret == "": break # 7. Close the file old_file.close() new_file.close()
- Binary version copy file [Extension]
# The copied file name should not be written dead. The user needs to input # The name of the new file becomes: old file name [copy] txt """ # a. Enter the file name old to be copied_ file_ name = input() # b. Find the first point on the right of the file name and assemble it through slicing: old file name [backup] suffix # 1. Open source file (old file) in read-only mode # 2. Open a new backup file (new file) in write only mode # 3. while True: # 4. Read the contents of the source file one point at a time # 5. If the content is read, write it into the write file # 6. If the content is not read, the file has been read, and break jumps out of the loop # 7. Close the file """ # a. Enter the file name old to be copied_ file_ name = input() old_file_name = input("Please enter the file name to be backed up: ") # b. Find the first point on the right of the file name and assemble it through slicing: old file name [backup] suffix pos = old_file_name.rfind(".") new_file_name = old_file_name[:pos] + "[backups]" + old_file_name[pos:] # 1. Open source file in read-only mode # Extension: Using Binary Reading and writing, you can read any format file_r = open(old_file_name, "rb") # rb: binary read-only opening (regardless of coding) # 2. Open a new backup file in write only mode file_w = open(new_file_name, "wb") # wb: binary mode write only open (regardless of coding) # 3. while True: while True: # 4. Read the contents of the source file one point at a time data = file_r.read(1024) # 5. If the content is read, write it into the write file if data: file_w.write(data) # 6. If the content is not read, the file has been read, and break jumps out of the loop else: break # 7. Close the file file_r.close() file_w.close()
7. [memory] file related operations
-
File rename: OS Rename (old file name, new file name)
-
Change the default directory: OS Chdir (changed path)
-
Get directory list: directory list variable = OS Listdir (specify a directory)
-
Determine whether the file exists: OS path. Exists (files to be judged)
-
""" 1. Import the module only once import os 2. use os Method in to complete the function os.Method name() """ import os # 1. Rename the file # Format: OS Rename (old file name, new file name) # os.rename("abc.txt", "abc final. txt") # 2. Delete file # Format: OS Remove (file name to be deleted) # os.remove("abc [backup]. txt") # 3. To create a folder, you can only create folders, not ordinary files # Format: OS MKDIR (name of folder) # os.mkdir("Zhang San") # 4. To delete a folder, only empty folders can be deleted # Format: OS Rmdir (name of folder to be deleted) # os.rmdir("Zhang San") # 5. Get the path of current work # Format: path variable = OS getcwd() # C:\Users\35477\Desktop\python40\day06 path = os.getcwd() # current work dir print(path) # C:\Users\35477\Desktop\python40\day06 # 6. Change the path # Format: OS Chdir (changed path) change dir # Switch to the previous path os.chdir("../") path2 = os.getcwd() print(path2) os.chdir(path) path2 = os.getcwd() print(path2) # 7. [key] obtain the file information of a directory and the name of a folder or file # Format: directory list variable = OS Listdir (specify a directory) # If you do not specify a directory, the default is the current path file_list = os.listdir() print(file_list) file_list2 = os.listdir("pytest") print(file_list2) # 8. Judge whether the document exists # Syntax format: OS path. Exists (files to be judged) # True is returned if the file exists, False is returned if the file does not exist ret = os.path.exists("info.txt") print(ret)
7.1. [application] batch modify file name
- Prefix files in batch
""" # 1. Get the directory information of pytest and return the list of file names # 2. Switch to the target path # 3. for traverses the list of file names and takes out an element # 4. Rename this element """ import os # 1. Get the directory information of pytest and return the list of file names name_list = os.listdir("pytest") # print(name_list) # ['lily.txt', 'mike.txt', 'rock.txt', 'tom.txt', 'yoyo.txt'] # 2. Switch to the target path os.chdir("pytest") # 3. for traverses the list of file names and takes out an element for name in name_list: # 4. Rename this element new_name = "[Dark horse products]-" + name os.rename(name, new_name) os.chdir("../")
- Batch restore file name
""" # 1. Get the directory information of pytest and return the list of file names # 2. Switch to the target path # 3. for traverses the list of file names and takes out an element # 4. Rename this element """ import os # 1. Get the directory information of pytest and return the list of file names name_list = os.listdir("pytest") # 2. Switch to the target path os.chdir("pytest") # 3. for traverses the list of file names and takes out an element for name in name_list: # 4. Rename this element tmp_str = "[Dark horse products]-" _len = len(tmp_str) new_name = name[_len:] os.rename(name, new_name) os.chdir("../")
8. [memory] conversion between string and container type
function | explain |
---|---|
Str (container variable) | Converts a container variable to a string |
Eval (string content) | Returns the result of the incoming string content. What you see in the string is converted into what you see |
# Conversion between string and container type # Str (container variable): converts a container variable to a string # Eval (string content): returns the result of the incoming string content. What you see in the string is converted into what you see # list user_list = [{"name": "rose", "age": 20, "sex": "male"}, {"name": "tom", "age": 21, "sex": "male"}] # List to string my_str = str(user_list) print(type(my_str), my_str) # f = open("abc.txt", "w") # f.write(user_list) # TypeError: write() argument must be str, not list # f.close() # character string my_str2 = "[{'name': 'xiaoming', 'age':15, 'sex':'male'}]" # String to list # eval(), convert whatever you see my_list = eval(my_str2) print(type(my_list), my_list, type(my_list[0]), my_list[0])
8.1. [memory] save the student's business card in the file
""" # 1. Open the file through the write only mode of with. After the execution of the statements in with, it will be closed automatically # 2. After converting the list into a string, write it into the file """ user_list = [{"name": "rose", "age": 20, "sex": "male"}, {"name": "tom", "age": 21, "sex": "male"}] # 1. Open the file through the write only mode of with. After the execution of the statements in with, it will be closed automatically with open("info.txt", "w") as file: # 2. After converting the list into a string, write it into the file file.write(str(user_list))
8.2. [memory] read the student's business card information from the file and write it into the list
""" # 1. Define an empty list, and the user will save the student information later # 2. Open the file through with and read-only # 3. File variables read() reads all the contents, and the returned contents are of string type # 4. Convert the read content into a list through eval and assign a value to the previous list # 5. Print the contents of the list outside the with """ # 1. Define an empty list, and the user will save the student information later # user_list = [] # 2. Open the file through with and read-only with open("info.txt", "r") as file: # 3. File variables read() reads all the contents, and the returned contents are of string type data = file.read() # 4. Convert the read content into a list through eval and assign a value to the previous list user_list = eval(data) # 5. Print the contents of the list outside the with print(type(user_list), user_list)
9. [application] file version student business card management system
9.1 [application] implementation idea of saving student business card information to file
1. adopt with Open files in write only mode, with After the execution of the statements inside, the automatic processing is closed 2. After converting the list into a string, write it to the file
# 1. Save business card information to file def save_stu(): # 1.1 add the prompt of saving information in the menu # 1.2 the main logic adds the option of saving business card information to file # 1.3 design of function of saving business card information to file with open("stu.txt", "w") as file: file.write(str(user_list))
9.2 [application] read the student business card information from the file to the business card system
0. Judge whether the file exists. If it does not exist, interrupt the function 1. adopt with Open file, read-only 2. File variable.read()Read all contents, and the returned contents are of string type 3. global Declare a list of global variables 4. Pass the read content through eval Convert to a list and assign a value to the global variable list
# 2. Load data def load_stu(): # 2.1 When the program starts, call the load data function in front of the loop # 2.2 judge whether the file exists or not, and interrupt the function if os.path.exists("stu.txt"): # 2.3 load data when the file exists # 2.4 open the file through with and read-only with open("stu.txt", "r") as file: # 2.5 document variables read() reads all the contents, and the returned contents are of string type data = file.read() # 2.6 global user statement_ List global variable global user_list # 2.7 convert the read content into a list through eval and assign a value to the list of global variables user_list = eval(data)