0

Suppose that I have a list X, and its contents to a single line of a file, i.e.

for var in X:
   if var <some conditions>:
         outfile.write("   "+var)

How can I do this so that each iteration of the loop is not written to a new line in the output file, i.e.

var1  var2  var3

rather than

var1
var2
var3

in outfile. I know this can be done with a print statement as print x, I can't find the equivalent for write.

1
  • 1
    It will write to the same line. Commented Jul 11, 2014 at 21:59

2 Answers 2

4

Unless your vars already contain trailing linebreaks you won't get multiple lines in your file.

However, you can simply strip off any trailing whitespace using rstrip():

outfile.write("   " + var.rstrip())

An even better solution would be creating a list with the items and join()ing it. Or simply pass a generator expression to the join() call:

outfile.write('   '.join(var for var in x if condition(var)))

The more explicit version would be this:

results = []
for var in x:
    if condition(var):
        results.append(var)
outfile.write('   '.join(results))
Sign up to request clarification or add additional context in comments.

4 Comments

This would result in: * var1 var2 var3, I don't think that's what OP want.(Ignore the *)
Thanks - embedding the condition in the join command saves me the need to have the for loop to begin with.
Exactly. If condition(x) is actually a function (and not just e.g. var > 5) in your case you could even use ' '.join(filter(condition, x))
Are you sure? Is it faster even for large datasets? I know that "small" generator expressions are more expensive than list comprehensions of the same size, but I assume that to change when the number of items grows.
0

As an alternative to ThiefMaster's excellent answer, the print function in Python3 allows you to specify a file object and an end.

vars = ['one','two','three']

with open("path/to/outfile","w") as outfile:
    for i, entry in enumerate(vars):
        if not condition(var):
            continue
        if i == len(vars):
            _end = ''
        else:
            _end = '    '
        print(entry, end=_end, file=outfile)

However using str.join is probable easier.

vars = ['one','two','three']
with open("path/to/outfile","w") as outfile:
    output_string = '    '.join(map(str.strip, [var for var in vars if condition(var)]))
    print(output_string, end='', file=outfile)
    # or outfile.write(output_string)

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.