简体   繁体   中英

Python redirect print output to file over loop

Simple questions but it's annoying me. I'm attempting to loop over a series of products of varying factors and then print each product to a file. I can get the code to work using the "with" statement but can't get it to work without it and I can't understand why. I am opening the file and then closing it as usual. Code is as follows:

f = open('out.txt', 'w')
for num1 in range(100,999):
    for num2 in range(100,999):
        product=num1*num2
        length=len(str(product))
        if length % 2 == 0:
            #halfway_point=
            print >> f, product
f.close()

It is failing on the last line with:

SyntaxError: invalid syntax

Not sure whether you are using Python 2 or Python 3. Either way, the fact that you see a SyntaxError suggests that an interactive interpreter session is being used.

I am going to assume that you are using Python 2. print >> expression, expression is a valid print statement in Python 2, and your usage of it in your code is correct. It simply means to redirect the string value of the second expression in the print statement to the file-like object given in the first expression. This statement is not available in Python 3.

Probably you are pasting the code into an interactive Python session, and if so you will need to add an extra new line to "close" the previous for loop before executing the close() , otherwise you will get a SyntaxError .

It will work if you add that code to a Python 2 script file and run it:

$ python2 somefile.py

or simply make sure to enter an extra new line if using the interactive interpreter.

For Python 3 you would do this:

print('{}'.format(product), file=f)

You can also use the same print() function in Python 2 by importing it from the __future__ module:

from __future__ import print_function

In both cases you should use the with statement as you mention in your question.

I don't know what print >> f, product means. But you can try this way :

f = open('out.txt', 'w')
for num1 in range(100,999):
    for num2 in range(100,999):
        product=num1*num2
        length=len(str(product))
        if length % 2 == 0:
              #halfway_point=
              # print >> f, product
              print(str(product) ) # print in the console
              f.write(str(product) + "\n")
f.close()

Your Syntax error is coming because of print >> f, product

Moreover you are not writing to file but printing to console.

You need f.write(str(product) + '\\n') line instead of print >> f, product (I don't know what print >> f, product means)

This works just fine for me in python3

f = open('out.txt', 'w')
for num1 in range(100,999):
    for num2 in range(100,999):
        product=num1*num2
        length=len(str(product))
        if length % 2 == 0:
            #halfway_point=
            f.write(str(product) + '\n')
f.close()

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