File operation of python
Opening and Closing of Files
open (File Name, Access Mode) - open Files
demo: file = open('test.txt', 'w')
close() - Close the file
demo: file = open('test.txt', 'w') file.close()
Access pattern description
- r: Open the file read-only. The pointer to the file will be placed at the beginning of the file, which is the default mode.
w: Open a file for writing only, overwrite it if it already exists, and create a new file if it does not exist. - A: Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is to say, the new content will be written to the existing content, if the file does not exist, create a new file for writing.
- rb: Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file, which is the default mode.
- wb: Opening a file in binary format is only for writing. If the file does not exist, create a new file.
- ab: Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file, that is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
- r+: Open a file for reading and writing, and the file pointer will be placed at the beginning of the file.
- w+: Open a file for users to read and write, and overwrite it if it already exists. If the file does not exist, create a new file.
- A+: Open a file for users to read and write. If the file already exists, the file pointer will be placed at the end of the file. When a file is opened, it will be appended. If the file does not exist, create a new file for users to read and write.
- rb+: Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
- wb +: Open a file in binary format for reading and writing, and overwrite it if it already exists. If the file does not exist, create a new file.
- ab+: Open a file user append in binary format, and if the file already exists, the file pointer will be placed at the end of the file.
write Write Data
Writing data to a file can be accomplished using write()
demo: file = open('test.txt', 'w') file.write('hello world') file.close()
Note: If the file does not exist, create the file. If the file exists, it is emptied first and then written to the data.
read Read read Data
Data can be read from a file using read(num), which represents the length of the data to be served from the file (in bytes), and if no num is passed in, it means reading all the data in the file.
demo: f = open('test.txt', 'r') #Up to 5 data reads content = f.read(5) print(content) print("-"*30) #Continue reading all the remaining data from the last read position content = f.read() print(content) #Note: Close file is required f.close() #Result: hello ----------------------------- world
- Note: If you open a file with open, if you use "r", you can omit it, that is, write only open('test.txt').
readlines Read Data
readlines, like read without parameters, reads the contents of the entire file in a row-by-row fashion, and returns a list in which the data of each row is an element.
demo: f = open('test.txt', 'r') content = f.readlines() print(type(content)) i = 1 for temp in content: print("%d:%s" % (i, temp)) i += 1 f.close()
readline Read Data
demo: f = open('test') content = f.readline() print("1:%s" % content) content = f.readline() print("2:%s" % content) f.close() //Result: 1:hello world 2:hello world
Make backups of files
Enter the name of the file, and the program automatically backs up the file.
demo: #Prompt for file name oldFileName = input("Please enter the name of the file to be copied:") #Open files in a read-only manner oldFile = open(oldFileName, 'rb') #Extract the suffix of the file fileFlagNum = oldFileName.rfind('.') fileFlagNum = 4 #rfind() returns the location of the last occurrence of the string, and - 1 if there is no match #rfind() method syntax: str.rfind(str, start=0 end=len(string)) if fileFlagNum > 0: #Using subscripts to obtain values [4:] fileFlag = oldFileName[fileFlagNum:] #Organize new file names newFileName = oldFileName[:fileFlagNum] + 'Duplicate' + fileFlag #Organizing new documents newFile = open(newFileName, 'wb') #Copy data from old files, line by line, to new files for lineContent in oldFile.readlines(): newFile.write(lineContent) #Close File oldFile.close() newFile.close()
Document-related operations
os.rename() rename
Rename (filename to be modified, new filename)
demo: import os os.rename('1.txt', '2.txt')
Os. remove (file name to be deleted)
demo: import os os.remove('2.txt')
os.getcwd() Gets the current directory
demo: import os os.getcwd()
os.chdir() Change the default directory
demo: import os os.chdir("../")
os.listdir() Gets a list of directories
demo: import os os.listdir("./")
os.rmdir() Delete folders
import os os.rmdir("demo")
Batch modification of file names
demo: #Batch prefix file name #Batch prefix file name import os funFlag = 1 #1 means add flag 2 means delete flag folderName = './renameDir/' #Gets all file names for the specified path dirList = os.listdir(folderName) #Traverse to output all file names for name in dirList: print(name) if funFlag == 1: newName = '[Shi Ge produce]-' + name elif funFlag == 2: num = len('[Shi Ge produce]-') newName = name[num:] print newName os.rename(folderName+name, folderName+newName)