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')
-
Output byte string
with open('data.txt', 'ab', True) as f: f.write('万物皆不自由\r\n'.encode('GBK'))
(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) ))
-
Output byte string
import os with open('data.txt', 'ab', True) as f: f.writelines((('世间当真有两全法'+os.linesep).encode('GBK'), ('江山深处抚你风华'+os.linesep).encode('GBK') ))
(3) line breaks
operating system | Newline |
---|---|
Windows | ‘\r\n’ |
*nux | ‘\n’ |
Tag works automatically with | os.linesep |