[英]Write multiple lines to file without using writelines() in Python3
I am trying to write multiple lines in a file using python, but without using writelines()我正在尝试使用 python 在文件中写入多行,但不使用writelines()
For now I planned to do so:现在我打算这样做:
header = ('-' * 42 +
'\nCREATION DATE: {}\n' +
'HOSTANME: {}\n' +
'PYTHON VERSION: {}\n' +
'SYSTEM: {}\n' +
'SYSTEM VERSION: {}\n' +
'SYSTEM RELEASE: {}\n' +
'MACHINE: {}\n' +
'PROCESSOR: {}\n' +
'-' * 42)
file.write(header)
But I don't know if it's the best way to do it.但我不知道这是否是最好的方法。
Thanks in advance.提前致谢。
Maybe use a dictionary:也许使用字典:
stuff = {
"CreationDate": "some_date",
"HostName": "some_host_name",
"PythonVersion": "some_version",
# ...
'Processor': "some_processor"
}
Then your data is stored in a nice, organized fashion.然后您的数据以一种漂亮的、有组织的方式存储。 After that, you just need to write some kind of function to convert the dictionary to a string similar to your desired output.之后,您只需要编写某种函数来将字典转换为类似于您想要的输出的字符串。 Something like this:像这样的东西:
header = str()
for key, value in stuff.items():
header += f'{key}: {value}\n' # use str.format() if don't have f-string support
file.write(f'{'-'*42}\n{header}{'-'*42}')
Hopefully that helps!希望这有帮助! :) :)
In this situation I would normally use '\\n'.join()
.在这种情况下,我通常会使用'\\n'.join()
。 You can pass any iterable of strings to '\\n'.join()
- this of course includes things like list comprehensions and generator comprehensions.您可以将任何可迭代的字符串传递给'\\n'.join()
- 这当然包括列表理解和生成器理解之类的东西。
For example, using the dict in Andrew Grass's answer, we could make his example more compact, if that's what you prefer:例如,使用 Andrew Grass 的答案中的 dict,我们可以使他的示例更加紧凑,如果这是您的喜好:
header = '\n'.join((f'{key}: {value}' for key, value in stuff.items()))
file.write('\n'.join(('-' * 42, header, '-' * 42)))
Of course, you could go further and put it onto one line, but in my opinion that would be too unreadable.当然,你可以更进一步,把它放在一行上,但在我看来,这太不可读了。
Here's a similar solution which is compatible with Python 3.5 and below (f-strings were introduced in Python 3.6).这是一个与 Python 3.5 及更低版本兼容的类似解决方案(在 Python 3.6 中引入了 f 字符串)。 This is even more compact, but perhaps slightly harder to read:这更紧凑,但可能更难阅读:
header = '\n'.join(map("{0[0]}: {0[1]}".format, stuff.items()))
file.write('\n'.join(('-' * 42, header, '-' * 42)))
You could use itertools.starmap
to make that last example a bit prettier:您可以使用itertools.starmap
使最后一个示例更漂亮一点:
from itertools import starmap
header = '\n'.join(starmap("{}: {}".format, stuff.items()))
file.write('\n'.join(('-' * 42, header, '-' * 42)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.