简体   繁体   中英

writing for loop variables to a single line of a file in python

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

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, ie

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM