0

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.

4
  • 1
    that works. you could also use a for loop. Commented Aug 12, 2019 at 23:15
  • 3
    What is the question? Welcome to SO. This isn't a discussion forum. Please take the time to read How to Ask and the other links found on that page. Commented Aug 12, 2019 at 23:19
  • 1
    What is the purpose of {} in the strings? You aren't calling .format(). Commented Aug 12, 2019 at 23:33
  • 1
    Why can't you use writelines? Commented Aug 12, 2019 at 23:43

2 Answers 2

1

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! :)

Sign up to request clarification or add additional context in comments.

Comments

0

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.