0

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

6
  • add newline="" Commented Dec 21, 2022 at 9:00
  • @Jean-FrançoisFabre, thank you, for your answer, but I also have tried this and it didn't help me Commented Dec 21, 2022 at 9:06
  • 2
    You show the initial file in one manner, then the second one in a different manner. A CSV file is a text file. Please show both file read with the same tool. That being said besides striping lines your code only adds an initial line: no need of the csv module for that... Commented Dec 21, 2022 at 9:14
  • the way you're reading your csv file is ... not the proper way. It's terrible. Use csv.DictReader instead. Plus edit your question to show where you inserted newline="" because it's not clear Commented Dec 21, 2022 at 9:18
  • @Jean-FrançoisFabre, I can't understand why I need to use "csv.DictReader" if I want to create and write a file, not to read. And can you please point me to why my way is terrible? I use "newline" in the part, where I create a csv file, so it is in the last "open with". Thanks for your reply Commented Dec 21, 2022 at 10:02

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.