1

I want to import a CSV file that contains information and it has random empty lines that I want to ignore and just skip over for example I have a .txt file that contains this information set up just like this:

Audi 90;200;Germany;22/10/19;150;
Bmw e46;350;Germany;22/10/19;100;
Mazda mx5;183;Japan;20/09/19;97;

Ford mustang;350;USA;21/04/19;278;
Lada;99999;Russia;20/11/19;99999;

And I want my code to output it like this:

Audi 90;200;Germany;22/10/19;150;
Bmw e46;350;Germany;22/10/19;100;
Mazda mx5;183;Japan;20/09/19;97;
Ford mustang;350;USA;21/04/19;278;
Lada;99999;Russia;20/11/19;99999;

My code for opening and setting up the table looks like this :

import csv
from tabulate import tabulate as tb

def file_opening():
    file = input("Enter .txt file name:")
    open(file + '.txt', 'r')
    fields = list(csv.reader(open(file + '.txt', 'r'), delimiter=';'))
    print(tb(fields, headers=['Car name', 'How many on road', 'Country of origin', 'Last update data', 'How many left', ''])
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Clique
  • 47
  • 2
  • 6
  • What is the problem with the code you've shown? Is there an error message? If so, then please include it in the question. – mkrieger1 Nov 20 '19 at 14:58
  • No problem, I just can't figure out a way to ignore empty lines in a .txt file. – Clique Nov 20 '19 at 15:04
  • So there *is* a problem, namely the code does *not* ignore empty lines? What does it do instead? – mkrieger1 Nov 20 '19 at 15:05
  • to skip empty lines you don't need `csv` but normal `open()`, `readlines()`, `write()` and `filter()` like in deleted answer – furas Nov 20 '19 at 15:05
  • @mkrieger1 The code prints out with all spaces – Clique Nov 20 '19 at 15:06
  • 1
    Possible duplicate of [Easiest way to ignore blank lines when reading a file in Python](https://stackoverflow.com/questions/4842057/easiest-way-to-ignore-blank-lines-when-reading-a-file-in-python) – mkrieger1 Nov 20 '19 at 15:16
  • Maybe you could also use `csv.DictReader` instead of `csv.reader`, see https://stackoverflow.com/questions/27707581/why-does-csv-dictreader-skip-empty-lines. But you would have to adjust the code a bit. – mkrieger1 Nov 20 '19 at 15:17

0 Answers0