1. Basic operation of files
-
File open format:
-
file = open (file path, read / write mode)
-
File path: you can write relative path or absolute path
-
Read / write mode: r (read) w (write) a (append)
-
-
-
After the file is opened, it must be closed, otherwise it will continue to consume server performance.
# File reading and writing is the same as our normal use of files # 1. Open the file # 2. Operation documents # 3. Close the file # Open the file and use the open function # Format: open (file_name, mode) using this function will return a file object # File path: you can write a relative path or an absolute path. The path needs to be passed in as a string # Read write mode: R (read only) w (write) a() append file = open('python.txt', 'r') print(file) # <_ io. TextIOWrapper name='python. Txt 'mode ='r' encoding ='utf-8 '> in windows, the default read / write format is gbk print(type(file)) # <class '_io.TextIOWrapper'> # Print the read content print(file.read()) # Close file file.close() # Why close the file? # When the file is open, it will remain connected. In this state, it will continue to consume memory, which is not conducive to server performance optimization (memory leakage) # Has the file object been released after closing the file? # No release print(file) # <_io.TextIOWrapper name='python.txt' mode='r' encoding='UTF-8'> # After the file is closed, the connection status with the file disappears, but the file object does not change # After the file is closed, the file object cannot perform any read and write operations because the file cannot be connected # ValueError: I/O operation on closed file. Cannot operate on a closed file print(file.read())
2. Read operation of file
-
Read: if a number is filled in (), the string of the specified character will be read. Each time the specified character is read, after a file is opened, multiple reads will continue to read the character backward. If all the characters are read, the empty string "" will be returned
-
Formats: file objects Read (maximum number of characters read at a time)
-
-
If the read file does not exist, an error will be reported directly
# The file can be read in 'r' mode # Read can read files # Open file file = open('python.txt', 'r') # read file # n: Pass in a value in read, which represents the maximum number of characters we read # If there is a text file in development, such as a web novel, which is 4 G in size and can be read at one time, the user will read such a large file in turn, which will consume extremely performance and wait too long # Therefore, in development, we often limit the value of read data. The maximum read characters are generally limited to (1024 * 1024) # Then we can only read three characters in turn by using read. How can we read the saved characters? # Every time a file is read, it will continue to read backward until the file is closed or the program ends, so you can use a loop to read # After all the file contents are read, the empty string ("") will be returned continuously while True: content = file.read(3) if content == '': break print(content) # Close file file.close()
-
readline: read one line of data each time, with \ n as the separator. After a file is opened, multiple read operations will continue to read backward. If all characters are read, an empty string "" will be returned
-
Formats: file objects readline()
-
-
readlines: read all the files at one time. After reading, save the text file in a line of text in the list
-
File object readlines()
-
# In addition to read, there are some reading methods # file open file = open('python.txt', 'r') # File operation # readline reads files in this way. Each line is separated by \ n. when the file is open, it will continue to read down until all files are read, and the empty string "" will be read # while True: # content = file.readline() # if content == '': # break # print(content,end='') # readlines reads all files, takes \ n as the separator, and saves all lines in the list as string elements for return # ['Wu Si Shu Tong, Zhang gaoqiu', 'empty mountains condense and clouds do not flow', 'raise your head to look at the bright moon', 'bow your head and think of your hometown'] content = file.readlines() print(content) # File close file.close()
3. File write operation
-
Open file using write mode 'w'
-
If the file exists, the source data is emptied
-
If the file does not exist, a new file will be created and no error will be reported
-
-
Use write to write characters
-
When writing files for reading and writing on windows computers, encoding needs to be used to specify the encoding format
-
Format: open (file path, read / write mode, encoding = encoding format)
-
# Write write # When the file is in read-write mode, 'w', the write operation of the file can be used # When the file is opened in write mode, if the opened file does not exist, a new file will be created without error # file = open('test.txt', 'w') # When the file is opened in write mode, if the opened file exists, the characters in the source file will be cleared # If you use a windows computer for development, you need to make the encoding format 'utf-8' when writing files # If you use linux or mac, the default is utf-8 encoding, and transcoding is not required file = open('python.txt', 'w', encoding='utf-8') # When we finish reading and writing files, we must use the same encoding format for writing and reading files # UnicodeDecodeError: 'gbk' codec can't decode byte 0x89 in position 14: illegal multibyte sequence print(file) # <_io.TextIOWrapper name='python.txt' mode='w' encoding='UTF-8'> # Write operation # file.write('I love Beijing Tiananmen Square, the sun rises on Tiananmen Square ') # If three pairs of quotation marks wrap the inner newline character when writing the string, will it be written? Will write format file.write(""" I Love Beijing Tiananmen , The sun rises on Tiananmen Square """) # writelines is used in conjunction with readlines to write a list of string elements to a file at one time # file.writelines('I love Tiananmen Square, Beijing ') lines = ['Wu Si, Shu Tong, Zhang gaoqiu\n', 'Empty mountains condense clouds and do not flow\n', 'look at the bright moon\n', 'Bow your head and think of your hometown\n'] file.writelines(lines) file.close()
4. File append
-
'a': file opening in mode
-
If the file does not exist, a new file is created
-
If the file exists, the string will be appended to the original file without emptying the source file
-
-
In the append mode, write is also used for file writing. There is no separate append method. The writing method is the same as that in the "w" mode
# 'a' mode write: append mode # In the append mode, you can append file characters and add new characters at the end of the original data # Open the file in append mode. If the file exists, the source file will not be emptied # file = open('python.txt', 'a', encoding='utf-8') # Open the file in append mode. If the file does not exist, create a new file # Open file file = open('bigdata.txt', 'a', encoding='utf-8') # Perform the append operation (Note: there is no append method, and the append operation is also written using write, but the source file will not be emptied) file.write('Those who disturb my heart are more worried today') # Close file file.close()
5. Expansion of file reading and writing mode
-
a: a a + ab ab+
-
a: Character append mode
-
a +: characters can be read in character append mode
-
ab: byte append
-
ab +: bytes can be read in byte append mode
-
-
w: w w + wb wb+
-
w: Character writing mode
-
w +: characters can be read in character writing mode
-
wb: byte write mode
-
wb +: bytes can be read in byte write mode
-
-
r: r r + rb rb+
-
r: Character reading mode
-
r +: character writing can be performed in character reading mode
-
rb: byte read mode
-
rb +: byte writing can be performed in byte reading mode
-
6. File backup case
# Requirement: the user enters a file name, backs up the file through file read-write operation, and changes the backup file name to: source file name [backup] suffix # 1. Get the file name typed by the user # 2. Backup through file read / write operation # 2.1. File name of the file after splicing backup # 2.2. read source file # 2.3. Write new file # 1. Get the file name typed by the user file_name = input('Please enter the name of the file you want to back up:') file = open(file_name, 'r', encoding='utf-8') # 2. Backup through file read / write operation # 2.1. File name of the file after splicing backup copy_file_name = file_name.replace('.', '[backups].') # Open new file copy_file = open(copy_file_name, 'a') # # Read old file data # content = file.read() # # Write new file # copy_file.write(content) # In general, files specify the maximum characters to be read in a single time # Cycle through reading and writing until all characters are read while True: content = file.read(3) if content == '': break copy_file.write(content) # Close file file.close() copy_file.close()
7. rename and remove
-
Rename can rename or move files
-
remove can delete files
# If you want to use these two methods, you need to import modules import os # Rename rename > > > is similar to mv in linux commands # Format: OS Rename (old file path, new file path) # Requirements: Python Txt to ABC txt # rename renames the file # The source file path must exist in rename # os.rename('bigdata.txt', 'abcd.txt') # Files can be moved through rename. The location of the move is determined according to the new file path. The name can also be modified after the move # os.rename('abcd.txt ',' file / abcd.txt ') # When moving a file, it must have a file name, otherwise it cannot be moved, and the name can be changed after moving # os.rename('abc.txt ',' file / a.txt ') # remove delete file > > > similar to rm in linux # You can delete a file without any prompt, but it will not appear in the recycle bin. You can't reply after accidental deletion. Be careful when deleting # os.remove('bigdata [backup]. txt ') # You can delete files in the specified path # If the deleted path does not exist, an error is reported (the path can use absolute path and relative path) # os.remove('File / a.txt ') # os.remove('python [backup]. txt ') # Permissionerror: [errno 1] operation not allowed: 'file' # You cannot delete a folder using remove os.remove('file')
8. Folder operation
-
mkdir: create an empty folder. You cannot create multi-level folders
-
rmdir: delete an empty folder. Folders with files cannot be deleted
-
getcwd: get the path of the working directory currently in use
-
chdir: switch the current working directory
-
listdir: query the directory structure of the specified directory, and save all file names in the directory in the form of string in the list for return
-
If nothing is filled in the brackets, it is the directory structure of the query working directory
-
If the path is filled in, it is a query for the specified directory
-
# When using the following functions or methods, you need to import the os module before using them import os # mkdir create folder # FileExistsError: [Errno 17] File exists: 'student' # If the created folder already exists, an error is reported # os.mkdir('student') # You can create folders under existing folders # os.mkdir('File / students') # FileNotFoundError: [Errno 2] No such file or directory: 'aaa/bbb' # os.mkdir('aaa/bbb') # Cannot create a folder if the parent directory does not exist # rmdir delete folder # FileNotFoundError: [Errno 2] No such file or directory: 'aaa/bbb' # If the deleted file no longer exists, an error will be reported # os.rmdir('student') # os.rmdir('File / students') # If the folder is not empty, can rmdir be used to delete it # OSError: [Errno 66] Directory not empty: 'file' # If the file is not empty, rmdir cannot be used for deletion, and recursive deletion is required # os.rmdir('File ') # getcwd can get the currently active working Directory > > similar to pwd in linux # /Users/day08/02 - Code # The default working directory is the root directory where our project is located print(os.getcwd()) # chdir switch working Directory > > similar to cd in linux # os.chdir('File ') # /Users/day08/02 - Code / file # print(os.getcwd()) # The directory structure under the directory specified by listdir > > > is similar to ls in linux commands # ['04-file writing. Py ',' file ',' ds_store ',' 08-folder operation. Py ',' Python [backup] Txt ',' 01 - file reading and writing experience Py ',' 00 - assignment explanation Py ',' 02 - reading of files py', 'test. Txt ',' 07 rename and remove Py ',' 06 - file backup case Py ',' 03 - other reading methods Py ',' 05 - file append py', '.idea'] # print(os.listdir()) # os.chdir('File ') # If the corresponding path is not written in listdir brackets, the path we use is the working directory. If the working directory is switched, the location of the directory structure is also changed # ['abcd.txt'] # print(os.listdir()) # Query the directory structure of the specified location. You can fill in the specified directory in listdir brackets, and we will query the directory structure # ['abcd.txt'] print(os.listdir('file'))
9. Case of batch modification of file name
# When using the following functions or methods, you need to import the os module before using them import os # mkdir create folder # FileExistsError: [Errno 17] File exists: 'student' # If the created folder already exists, an error is reported # os.mkdir('student') # You can create folders under existing folders # os.mkdir('File / students') # FileNotFoundError: [Errno 2] No such file or directory: 'aaa/bbb' # os.mkdir('aaa/bbb') # Cannot create a folder if the parent directory does not exist # rmdir delete folder # FileNotFoundError: [Errno 2] No such file or directory: 'aaa/bbb' # If the deleted file no longer exists, an error will be reported # os.rmdir('student') # os.rmdir('File / students') # If the folder is not empty, can rmdir be used to delete it # OSError: [Errno 66] Directory not empty: 'file' # If the file is not empty, rmdir cannot be used for deletion, and recursive deletion is required # os.rmdir('File ') # getcwd can get the currently active working Directory > > similar to pwd in linux # /Users/day08/02 - Code # The default working directory is the root directory where our project is located print(os.getcwd()) # chdir switch working Directory > > similar to cd in linux # os.chdir('File ') # /Users/day08/02 - Code / file # print(os.getcwd()) # The directory structure under the directory specified by listdir > > > is similar to ls in linux commands # ['04-file writing. Py ',' file ',' ds_store ',' 08-folder operation. Py ',' Python [backup] Txt ',' 01 - file reading and writing experience Py ',' 00 - assignment explanation Py ',' 02 - reading of files py', 'test. Txt ',' 07 rename and remove Py ',' 06 - file backup case Py ',' 03 - other reading methods Py ',' 05 - file append py', '.idea'] # print(os.listdir()) # os.chdir('File ') # If the corresponding path is not written in listdir brackets, the path we use is the working directory. If the working directory is switched, the location of the directory structure is also changed # ['abcd.txt'] # print(os.listdir()) # Query the directory structure of the specified location. You can fill in the specified directory in listdir brackets, and we will query the directory structure # ['abcd.txt'] print(os.listdir('file'))