catalogue
3. Another method of file manipulation
4. File operation related functions
readline() function and readlines() function
file operation in Python
For reading and writing files on disk, file I/O:input input / output
File operation steps: 1. Open the file
2. Read and write files
3. Close the file
Steps for writing a file: 1. open the file
2. write ()
3. close the file ()
Steps to read a file: 1. open the file
2. read the file
3. close the file ()
open() function
Parameter 1: file path
Path url uniform resource locator
Absolute path: always start from the root folder. Windows uses (C:, D:) as the root directory, while Linux or OS X systems use / as the root folder. Just like filling in the harvest address for online shopping, it is accurate from a province to your house number. Example of absolute path: for example, C:\users\Downloads\ XX txt
Relative path: refers to the location of the file relative to the current working directory. For example, the current working directory is "C:\Windows\System32", if the file demo Txt is located in the System32 folder, so demo The relative path of TXT is expressed as ".\demo.txt" (where. \ indicates the current directory), and (.. \ indicates the upper level directory of the current directory)
Parameter 2: open mode
pattern | describe |
---|---|
r | Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode. |
rb | Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. |
r+ | Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. |
rb+ | Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. |
w | Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. |
wb | Open a file in binary format for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. |
w+ | Open a file for reading and writing. Overwrite the file if it already exists. If the file does not exist, create a new file. |
wb+ | Open a file in binary format for reading and writing. Overwrite the file if it already exists. If the file does not exist, create a new file. |
a | Open a file for appending. If the file already exists, the file pointer is 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 to write. |
ab | Open a file in binary format for appending. If the file already exists, the file pointer is 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 to write. |
a+ | Open a file for reading and writing. If the file already exists, the file pointer is placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing. |
ab+ | Open a file in binary format for appending. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, create a new file for reading and writing. |
Parameter encoding: optional parameter to set the character set in the file. If it is a binary file, it is not necessary to set the character set. For example, encoding = "utf-8"
1. File write
# file operation in python # Write operation # 1. Open file fp = open('./1.txt', 'w', encoding='utf-8') print('file name:', fp.name, ' pattern:', fp.mode, ' character set:', fp.encoding) # Print file name, mode, and character set # 2. Write content fp.write('hello python') # 3. Close file fp.close() print("File closed:", fp.closed) # Judge whether to close. If closed, return True; otherwise, return False
# result file name: ./1.txt pattern: w character set: utf-8 File closed: True
At this time, find the path of the python file, and you can find the generated 1 TXT text file, or double-click directly in the pycharm project to open and display hello python
2. File read
# file operation in python # read operation # 1. Open file fp = open('./1.txt', 'r', encoding='utf-8') # read-only print('file name:', fp.name, ' pattern:', fp.mode, ' character set:', fp.encoding) # Print file name, mode, and character set # 2. Read content res = fp.read() # fp.seek(0) # At this time, the cursor is at the end. If you do not add the seek function to move the pointer to the beginning, the read of the code block reads the empty content behind the cursor # res = fp.read(2) # Read the first two contents print(res) # 3. Close file fp.close() print("File closed:", fp.closed) # Judge whether to close. If closed, return True; otherwise, return False
# result file name: ./1.txt pattern: r character set: utf-8 hello python File closed: True
3. Another method of file manipulation
# Advanced writing for file writing with open('./2.txt', 'a+', encoding='utf-8') as fp: fp.write('123abcd') fp.seek(0) # At this time, the cursor is at the end. If you do not add the seek function to move the pointer to the beginning, the read of the code block reads the empty content behind the cursor res = fp.read() print(res)
# result 123abcd
After the file is written, add fp Seek (0), move the cursor to the beginning before reading
4. File operation related functions
writelines() function:
For the write() function: only strings can be written, and int types and container types cannot be written
Writelines() function: if you want to write data of a container type, you should use the writelines() function
Note: for the writelines() function, the data in the container cannot be of type int, but must be a string
var = ['hello', " world", ' 1', ' 1ab2'] with open('./3.txt', 'w+', encoding='utf-8') as fp: fp.writelines(var) fp.seek(0) # At this time, the cursor is at the end. If you do not add the seek function to move the pointer to the beginning, the read of the code block reads the empty content behind the cursor res = fp.read() print(res)
# result hello world 1 1ab2
readline() function and readlines() function
var = ['hello\n', "world\n", '123456\n', '1ab2'] with open('./3.txt', 'w+', encoding='utf-8') as fp: fp.writelines(var) fp.seek(0) res = fp.readline() # Read only one row print(res) res = fp.readline() # Read the second line print(res) res = fp.readline(2) # Read the first two of the third line print(res) fp.seek(0) res = fp.readlines() # Read multiple rows of data at a time, and each row as an element returns a list print(res)
# result hello world 12 ['hello\n', 'world\n', '123456\n', '1ab2\n']
seek() function
file.seek(0) \
file.seek(3) \
\,
file.seek(0,0) is moved to the beginning of the file by default or abbreviated as seek(0)
file.seek(x,1) means to move x (positive) bytes backward from the current pointer position. If x is a negative number, it means to move x bytes forward from the current position
file.seek(x,2) means to move x (positive) bytes forward and backward from the end of the file. If x is negative, it means to move x bytes forward from the end
truncate() function
Explanation: by default, it starts from the first character in the first line of the file, truncates to the size-1 character, and truncates the following string. If the size is 0, it is truncated from the first character (including the first character) in the first line to the last.
Syntax: file Truncate (size) \y (size is not the same as size 0)
Parameter: size -- the size of the file to be truncated (at most) if the optional parameter exists.
Return value: None
Code demonstration
var = ['hello ', " world ", 'nihao ', 'shijie'] with open('./4.txt', 'w+', encoding='utf-8') as fp: fp.writelines(var) # fp.truncate(3) fp.seek(0) res = fp.read() print(res) res = fp.read() print(res)
# result hello world nihao shijie
If after opening the comment (fp.truncate(3)):
# result hel