8.1 documents and folders
Supporting Python teaching video
8.1. 1 document
① File open
File object = open("file name", "access mode")
The access mode is as follows:
'r' read only: if the file does not exist, an error will be reported, and write operation is not supported.
r +: if the file does not exist, an error is reported. It supports reading and writing.
'w' write: if the file does not exist, create a new file and overwrite the original content when writing.
w +: if the file does not exist, it will be created, readable and writable.
'a' append: if the file does not exist, create a new file, and append new content on the basis of the original content when writing.
'a' append: if the file does not exist, a new file will be created to read and append content.
The access mode is "r" mode by default.
The binary access mode is as follows:
rb: an error is reported as long as the file does not exist. The file pointer is placed at the beginning of the file for binary reading.
rb +: read / write binary. However, if the file does not exist, an error is reported.
wb: as long as the file does not exist, create a new file, ask for the price, press the pointer at the beginning, and overwrite the original content with the new content. Write binary data.
wb +: readable and writable binary data. If the file does not exist, it is created.
ab: created if the file does not exist. Append binary data.
ab +: readable and appendable binary data. If the file does not exist, it is created.
Summary: r is read, w is overwrite write, and a is append write. The addition of b after the three represents the operation of binary data, rather than simple content. Plus + means to expand its function. For example, if there was no write function before, let you have write function now.
② Read / write operation
File object write("content")
File object Read refers to reading fixed length data. If this parameter is omitted, all are read. Remember that \ nthe newline character also takes up one byte.
File object readlines() reads all the lines, and encapsulates each line as an element of the list for detailed processing.
File object readline() can only read one line at a time, and the next line will be read when the cursor moves. Because read-only takes one line, there is no \ nline break.
③ Close and move file pointer operations
File object close()
File object Seek (offset, start position) moves the file pointer
File object tell() gets the position of the current cursor
Starting position: 0 represents the beginning position, 1 represents the current position, and 2 represents the end position of the file.
Offset: for example, if the start position is the start position and the offset is 5, the file pointer is on the sixth byte.
seek() is the key function to realize random reading and writing, that is, where we want to write or read, we should cooperate with seek() to move the cursor there for other function operations.
8.1. 2 practical part
Create file and write content
a = open('1.txt','w') a.write("""aaaa bbbb cccc""") a.close()
Read how many characters there are and read the content
a = open('1.txt','w') a.write("""aaaa bbbb cccc""") a.close()#When the file is closed, the time mark will be refreshed to the correct position when it is opened again. a = open('1.txt','r',encoding="utf-8") print(len(a.read()))#The cursor has moved to the end a.seek(0)#So we're going to move the cursor to the beginning print(a.read())#If the cursor is not at the beginning, the read result must be empty a.close()
Remember: whether reading or writing, the cursor will move accordingly, so we should always be aware of the approximate position of the cursor at this time. Otherwise, when you operate later, there will be many operations that you think are wrong. Don't you know that it's just the wrong position of the cursor!!!
Try readlines() and readline()
a.seek(0) list = a.readlines() print(len(list)) for i,x in enumerate(list): if(x.find('a') != -1): del list[i] print(list)
Process all eleme n ts without the replace() method
a.seek(0) list = a.readlines() for i,x in enumerate(list): sub = x.find('\n') if(sub != -1): list.insert(i+1,x[:sub]) del list[i] print(list)
print(list) a.seek(0) print(a.readline()) print(a.tell()) a.close()
The tell() method can directly take the current cursor at the first few bytes.
The cursor is at the sixth byte. The next operation will start from the position of the sixth byte.
8.1. 3 file backup
In fact, file backup is a practical operation. What we mean is to provide the specific path of the file and take the name of the file.
File path = r"C:\Users\muqua\Desktop\plugin\com.sdk.demo.vlw.dll" endSub = File path.rfind(".") preSub = File path.rfind("\\") print(File path[preSub+1:endSub])
File path = r"C:\Users\muqua\Desktop\plugin\com.sdk.demo.vlw.dll" endSub = File path.rfind(".") preSub = File path.rfind("\\") print(File path[preSub+1:endSub]) Backup path = File path[:preSub] +"\\" +File path[preSub+1:endSub] + "_backups"+File path[endSub:] print(Backup path) Old file = open(File path,"rb") Backup file = open(Backup path,"wb") while True: Read data = Old file.read(1024) if(len(Read data) == 0): print("Write data ok!") break else: Backup file.write(Read data) Old file.close() Backup file.close()
In fact, you can directly try to write all data without 1024 data block cyclic writing. However, you may encounter insufficient cache, resulting in write failure. Backup files Write (old file. read())
8.2.1 os module
For folders, it is recommended that you use the OS module. It can operate on both files and folders.
Import os # import os module
os.rename('old file name ',' new file name ') renames the file. If the target file cannot be found, an error will be reported.
os. Realm ('old folder name ',' new folder name ') renames the folder. If the target folder cannot be found, an error will be reported.
os. Remove (target file name) deletes the file, cannot delete the folder!
os. Rmdir (folder name) deletes the folder.
os. MKDIR (the name of the folder) creates a folder (if the folder already exists, an error is reported.)
os.getcwd() is a very important function. In actual development, the most commonly used function is the current file path of the program. Because the program we write should be arranged in our own folder.
os. Chdir (modified current directory) is not recommended!! If we want to operate other directories, we can directly provide the absolute path. Do not change the current directory at will. This is very confusing in development.
os. Listdir (directory) returns everything under the provided directory and returns a list. If no parameters are provided, everything in the current directory is returned by default. In some cases, you need to traverse them. To find a file. Very practical function!
Then the problem comes. We said that if the target file cannot be found, some methods may report errors. But our program is not allowed to report errors and run away directly! What shall I do? Are we going to carry out relevant detection and processing! This is the exception handling we will talk about in the next chapter!
import os #os.rename("1.txt", "change to 1.txt") #os.rename("folder 1", "change folder 1") #os.remove("3.txt") #os.rmdir("Folder 2") #os.mkdir("folder") print(os.getcwd()) #os.chdir("C:\\") # Really, really, not recommended!!! print(os.getcwd()) print(os.listdir())