0

I'm setting a code in python 2.7 where I have to write the result of a list variable in logfile

I tried logFile.write(.format(var))
also logFile.write.print(var)

var = []
logFile.write(var)
5
  • 1
    Then ? what's your question?
    – Adam
    May 29, 2019 at 8:54
  • What's the format you'd like the resulting file to be in? Do you want each of the values in the list to be on a separate line? Do you want something like a csv? Does it need to be structured logging?
    – martyn
    May 29, 2019 at 8:58
  • How can I write the result of var in logfile ?
    – Siham MB
    May 29, 2019 at 8:58
  • I want all the values in the list to be on a separate line in the logfile
    – Siham MB
    May 29, 2019 at 9:00
  • 1
    please describe more of your code. What is logfile for example?
    – Flo
    May 29, 2019 at 9:06

2 Answers 2

1

This is a very broad question; I'd recommend checking the basic python tutorial first to see what you'd actually need.

There are different options, depending on the format you'd like the resulting output file to be in.

Simple line-by-line

Just write the output of each of the variables in the list to a file, line-by-line:

import os

filename = "output.txt"

with open(filename, "w") as file_handle:
    for value in var:
        file_handle.write(value + os.linesep)

What this does:

  1. open a file handle in write mode, using a context manager. This assures the file will be closed afterwards and all values will be written
  2. iterate through all values in the array
  3. write each of the value to the file handle, followed by a line separator (\n on nix-like systems)
0
0

This can be achieved using the python's join() method:

logFile.write("\n".join(var))

Try this and tell me if this works.


Requesting old members to help me properly formulate the answer.

1
  • The works only of all the items in the var list are strings—something the OP never stipulated. Good guess. You should mention that requirement in your answer.
    – martineau
    May 29, 2019 at 9:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.