六、Python IO与异常 之 3、写文件

3、写文件

(1)write(str或bytes)

说明:输出字符串或字节串(只有以二进制模式(b模式)打开的文件才能写入字节串)

  • 输出字符串

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

在这里插入图片描述

  • 输出字节串

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

在这里插入图片描述

(2)writelines(可迭代对象)

说明:输出多个字符串或多个字节串

  • 输出字符串

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

在这里插入图片描述

  • 输出字节串

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

在这里插入图片描述

(3)换行符

操作系统 换行符
Windows ‘\r\n’
*nux ‘\n’
代码自动兼容 os.linesep

猜你喜欢

转载自blog.csdn.net/qq_36512295/article/details/94739831