Example explanation of saving python running results to local file
- 2021-07-13 05:48:10
- OfStack
1. Create files and save data
1. Open the txt file using the built-in open function in python
#mode Mode
#w Only write can be operated r Read only a Append to a file
#w+ Readable and writable r+ Readable and writable a+ Readable and appendable
#wb+ Write binary data
#w Mode opens the file, if there is data in the file, write the content again, and the original will be overwritten
file_handle=open('1.txt',mode='w')
2. Write data to a file
2.1 write Writing
#\n Line break
file_handle.write('hello word How do you do \n')
2.2 The writelines () function writes the string in the list to the file, but does not wrap the line automatically. If you need to wrap the line, add the newline character manually
# Parameter Must be 1 A string-only list
file_handle.writelines(['hello\n','world\n',' How do you do \n',' Wisdom tour \n',' Zhengzhou \n'])
Step 3 Close the file
file_handle.close()
2. Open the file and read the information in the file
1. Open the file
# Use r Open the file in mode and read the file
# The mode of opening a file is the default r Mode, if you just read the file, you can not fill it out mode Mode
file_handle=open('1.txt',mode='r')
2. Read the contents of the file (3 methods)
2.1 read (int) Function
Read the contents of the file. If the read length is specified, it will be read by dark battle length, and all data will not be read by default
content=file_handle.read(20)
2.2 readline (int) Function
By default, the data parameter of 1 line of the file is larger than the length of 1 line, and the value is read by 1 line. If it is less than the length of 1 line, the specified length is read
content=file_handle.readline(20)
2.3 readlines () Function
The data of every 1 row will be returned as 1 element in the list, and the data of all rows will be read
contents=file_handle.readlines()
Step 3 Close the file
file_handle.close()
3. Function tell () to get the cursor position
#tell() Function Returns the position of the cursor in the current file
file_handle=open('1.txt')
# Read first 1 Row data
content=file_handle.readline()
print(content)
# Gets the position of the cursor
number=file_handle.tell()
print(number)
4. Function seek () for adjusting cursor position
#\n Line break
file_handle.write('hello word How do you do \n')
0
Example
1. Store the information of each member from the list into a file, and then take it out of the file and assemble it into the original list
#\n Line break
file_handle.write('hello word How do you do \n')
1
2.
#\n Line break
file_handle.write('hello word How do you do \n')
2