Six, Python IO and anomalies 3, write files

3, write files

(1)write(str或bytes)

Description : the output string or byte string (binary mode only (b mode) can be written to open a file byte string)

  • Output string

    with open('data.txt', 'a', True, 'GBK') as f:
        f.write('痴迷、淡然\r\n')
    

Here Insert Picture Description

  • Output byte string

    with open('data.txt', 'ab', True) as f:
        f.write('万物皆不自由\r\n'.encode('GBK'))
    

Here Insert Picture Description

(2) writelines (iterables)

Description : a plurality of output byte strings or more strings

  • Output string

    import os
    with open('data.txt', 'a', True, 'GBK') as f:
        f.writelines((('我心里那一座天下'+os.linesep),
                      ('你坐镇笑靥如桃'+os.linesep)
                     ))
    

Here Insert Picture Description

  • Output byte string

    import os
    with open('data.txt', 'ab', True) as f:
        f.writelines((('世间当真有两全法'+os.linesep).encode('GBK'),
                      ('江山深处抚你风华'+os.linesep).encode('GBK')
    
                     ))
    

Here Insert Picture Description

(3) line breaks

operating system Newline
Windows ‘\r\n’
*nux ‘\n’
Tag works automatically with os.linesep

Guess you like

Origin blog.csdn.net/qq_36512295/article/details/94739831