2

I have been learning python for a week. but I'm not sure how I can save the result as a file.

def process_rows(self, rows):
    for row in rows:
        self.rownum+=1
        print(rownum)

I think there will be over 400000 results. But Termial shows only 8000 results from 441810 to 450000.

I wanna save the result on a .txt file and read. I have changed my code as follows.

def process_rows(self, rows):
    f = open("output_file", 'a+')
    for now in rows:
        self.rownum +=1
        f.write(rownum + "\n")
    f.close()

But exception error has occurred.

TypeError: unsupported operand type(s) for +: 'int' and 'str'
ERROR:tornado.application:Uncaught exception in /conn 
File "/usr/lib/python2.7/dist-packages/tornado/websocket.py", line 415, in _run_callback
  callback(*args, **kwargs)
File "server.py", line 98, in process_rows
  f.write(rownum + "\n")
NameError: global name 'rownum' is not defined
Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
dieter
  • 55
  • 7

2 Answers2

0

This should work:

def process_rows(self, rows):
    f = open("output_file", 'a+')
    for now in rows:
        self.rownum +=1
        f.write(str(self.rownum) + "\n")
    f.close()

You had two errors in one line: 1) omitting 'self.'; 2) adding int + string, as message said.

If you read doc for print and write, as suggested, you would discover that print automatically converts objects to string, using the default formatting, which write does not. When writing to a file, one often wants to specify the exact formatting.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
-1

There are two ways to go:

  1. redirect print output to a file.

Note that print takes an integer rownum and displays str() of it.

def process_rows(self, rows):
    f = open("output_file", 'a+')
    for row in rows:
        self.rownum+=1
        print(rownum, file = f)
  1. use correct data types for addition operation.

What you are doing in your second snippet is adding an integer rownum to a string '\n', which is not a valid operation. You need to convert integer to a corresponding string first:

def process_rows(self, rows):
    f = open("output_file", 'a+')
    for now in rows:
        self.rownum +=1
        f.write(str(rownum) + "\n")
    f.close()
Dima Lituiev
  • 12,544
  • 10
  • 41
  • 58