Home » excel » excel – Python: How to write/print all records to the file

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

Posted by: admin May 14, 2020 Leave a comment

Questions:

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()
How to&Answers:
# 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()

Answer:

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

Answer:

Just little modification in your code:-

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