如何使用多行字符串在文件中写入多行?我真的很想优化下面的代码

How to write multiple lines in a file using multiline string? I really want to optimize the below code

我正在使用 file_name.write 写多行,考虑到空间来写一个文件。

代码:

    file_handle.write('$TTL 1h\n')
    file_handle.write('@\tIN\tSOA\tns1.test.nimblestorage.com.\tis-ops.hpe.com. (\n'
                      )
    file_handle.write('\t\t\t%s\t; serial\n' % serial_number)
    file_handle.write('\t\t\t3h\t; refresh\n')
    file_handle.write('\t\t\t30m\t; retry\n')
    file_handle.write('\t\t\t30d\t; expire\n')
    file_handle.write('\t\t\t5m )\t; minimum\n')
    file_handle.write('\t\tNS\tns1.test.nimblestorage.com.\n')
    file_handle.write('\t\tNS\tns2.test.nimblestorage.com.\n')
    file_handle.write('\n')

但我需要一些多行字符串代码,所有行都在一个文件中。

使用三引号:

file_handle.write('''$TTL 1h
@\tIN\tSOA\tns1.test.nimblestorage.com.\tis-ops.hpe.com. (
\t\t\t{serial}\t; serial
...
'''.format(serial=serial_number))

需要 multi-line 个字符串是有原因的,在这种情况下,John Zwinck 的答案是好的。但是,如果您希望它们用于文件 I/O 优化:

不打扰

Python 已经为您做了优化:请参阅 https://docs.python.org/3/library/functions.html#open

中的缓冲选项