Ashat Usbekof
Ashat Usbekof

Reputation: 35

Python: How to write/print all records to the file

I have code that reads data from a Excel spreadsheet, then performs some simple transforms on the data, and save results into the text file.

All working fine except one problem- I can see only last record. Seems loop overwriting all records... How can I get all records?

from openpyxl import load_workbook
# The source xlsx file is named as source.xlsx
wb=load_workbook("/home/test/Downloads/test.xlsx")
ws = wb.active
first_column =ws['A']
second_column =ws['B']
# Print the contents
for x in xrange(len(first_column)):
    A = str(first_column[x].value)
    B = str(second_column[x].value)
    C = str(len(B.split()))
    PRN = A+B+C
    file = open('filename', 'w')
    file.write(PRN)
    file.close()

Upvotes: 1

Views: 719

Answers (3)

Nathan
Nathan

Reputation: 3648

when you open a file it erases all previous data. Use:

file = open('filename', 'a')

This appends to the file rather than rewriting it. This does have the result that running the program multiple times will make the final result longer and longer. So you can also use:

file = open(filename', 'w')

for x in xrange(len(first_column)):
     file.write(text)
file.close

Upvotes: 1

dx247
dx247

Reputation: 24

# Print the contents
file = open('filename', 'w')

for x in xrange(len(first_column)):
    A = str(first_column[x].value)
    B = str(second_column[x].value)
    C = str(len(B.split()))
    PRN = A+B+C
    file.write(PRN)

file.close()

Upvotes: 1

Narendra
Narendra

Reputation: 1529

Just little modification in your code:-

PRN = A+B+C
    file = open('filename', 'a')
    file.write(PRN+"\n")
    file.close()

Upvotes: 1

Related Questions