1. Open the txt file
file_handle=open('1.txt',mode='w')
The above function parameters are (1. file name, mode mode)
The mode mode has the following types:
#w can only operate and write r, can only read a, append to the file #w+ readable and writable r+ readable and writable a+ readable and appendable #wb+ write binary data #w mode to open the file, if there is in the file Data, writing the content again will overwrite the original
2. Write data to the file
The first way to write:
# 2.1 write write #\n newline character file_handle.write('hello word Hello\n')
The second way of writing:
# 2.2 The writelines() function will write the strings in the list into the file, but it will not wrap automatically. If you need to wrap, manually add a newline #The parameter must be a list that only stores strings file_handle.writelines(['hello \n','world\n','Hello\n','Zhiyou\n','Zhengzhou\n'])
3. Close the file
file_handle.close()