简体   繁体   中英

Write csv file from text file without empty lines in Python

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

Txt file looks like this:

在此处输入图像描述

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

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM