Home >Backend Development >Python Tutorial >PYTHON: How to increase the content of a file
Problem scenario:
During the test, hundreds of accounts need to be created. I wrote a script to automatically generate accounts, but I want to write the generated accounts into a file.
The following write() method is used at the beginning. The content of the original file will be cleared first and then new things will be written. Each time the file contains the latest generated account
mobile = Method.createPhone() file = r'D:\test.txt'with open(file, 'w+') as f: f.write(mobile)
Analysis:
After checking the information, about the mode parameter of open():
'r': read
'w': write
'a': append
'r ' == r w (readable and writable, if the file does not exist, an error (IOError) will be reported)
'w ' == w r (readable and writable, the file will be created if it does not exist)
'a ' ==a r (can be appended and writable, the file will be created if it does not exist)
Correspondingly, if it is a binary file, just add a b:
'rb' 'wb' 'ab' 'rb ' 'wb ' 'ab '
Solution:
It is found that the method is used incorrectly. If new accounts are continuously generated and written, append 'a' should be used
After changing to the following, the solution is:
mobile = Method.createPhone()
file = r'D:\test.txt'with open(file, 'a ') as f:
f.write(mobile '\n') #Add\nNewline display
The above is the detailed content of PYTHON: How to increase the content of a file. For more information, please follow other related articles on the PHP Chinese website!