Home >Backend Development >Python Tutorial >PYTHON: How to increase the content of a file

PYTHON: How to increase the content of a file

anonymity
anonymityOriginal
2019-05-27 10:53:324676browse

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)

PYTHON: How to increase the content of a file

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn