Home > Mobile >  Write csv file from text file without empty lines in Python
Write csv file from text file without empty lines in Python

Time:12-29

I trying to create csv file from txt file with only one row.

Txt file looks like this:

enter image description here

My code is:

row = []
with open('vehicles.txt', 'r', encoding='utf-8') as r:
    r = len(r.readlines())
with open('vehicles.txt', 'r', encoding='utf-8') as f:
    for i in range(r):
        data = {
            'vehicle': f.readline().strip()
        }
        row.append(data)
        csv_title = ['vehicle']
with open('vehicle.csv', 'w', encoding='utf-8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=csv_title)
    writer.writeheader()
    writer.writerows(row)

But csv file creates with empty rows

enter image description here

How can I remove these empty lines? When I print this in the terminal, it goes without empty lines

edit:

Adding a newline="" also doesn't help. The csv files still goes with empty rows

CodePudding user response:

well, my issue was, that the txt file has some symbols, that made a empty rows, and cause the txt file is large it hard to notice this symbols.

So I changed the encoding to utf-16 and it made me csv file as I want it to be maded

  • Related