Reputation: 65
I am trying to write multiple lines in a file using python, but without using 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.
Upvotes: 0
Views: 101
Reputation: 305
In this situation I would normally use '\n'.join()
. You can pass any iterable of strings to '\n'.join()
- this of course includes things like list comprehensions and generator comprehensions.
For example, using the dict in Andrew Grass's answer, we could make his example more compact, if that's what you prefer:
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). 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:
from itertools import starmap
header = '\n'.join(starmap("{}: {}".format, stuff.items()))
file.write('\n'.join(('-' * 42, header, '-' * 42)))
Upvotes: 0
Reputation: 252
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! :)
Upvotes: 1