Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove blank line from CSV file when reading or writing

I’m trying to print the contents of a CSV file row by row, there’s only one row of data (CSV Library adds an extra row at the end of the file for some reason) however when the contents are printed below the contents of the file is outputted twice. From my understanding this is due to the extra blank line inputted by the CSV Library. I’m looking for a way to ignore this blank line or get rid of it entirely.

hourList = []
    with open("reports/totalHours.csv", "r") as report:
        reader = csv.reader(report)
        for row in reader:
            hourList.append(row)
            print(hourList)

the contents of totalHours.csv:

000,40

cmd output of script

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['000', '40']]

[['000', '40'], []]

PS. I’m writing to the file initially using Append as this is the best method that achieves my required output.

>Solution :

This implementation will ignore the blank line at the bottom of the file, but it will also ignore any other blank lines in the file:

hourList = []
    with open("reports/totalHours.csv", "r") as report:
        reader = csv.reader(report)
        for row in reader:
            if len(row) > 0:
                hourList.append(row)
                print(hourList)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading