Search code examples
python-3.xreadfile

python trim tab from file


I am importing a tab separated file.

import csv
with open(logfile) as f:
    csvlines = csv.reader(f,delimiter='\t')
    for row in csvlines:
        print(row)
 prints [' mike            john              steve']

Is there a way to have it print

 make|steve|john

I tried using csv.DictReader but since it's not a true csv file is mucks up


Solution

  • Unable to reproduce:

    import csv
    logfile = "t.txt"
    
    with open(logfile,"w") as f:
        f.write('mike\tjohn\tsteve\n')
        f.write('mike           john           steve\n')  # no tabs, just spaces
    
    with open(logfile) as f:
        csvlines = csv.reader(f,delimiter='\t')
        for row in csvlines:
            print(row) 
    

    Output:

    ['mike', 'john', 'steve']
    ['mike           john           steve']
    

    You probably have a space seperated file before you .... hence all are matched into one column.


    You can parse a space separated file by:

    with open(logfile) as f:
        csvlines = csv.reader(f,delimiter=' ', skipinitialspace=True)
        for row in csvlines:
            print(row)  
    

    Wich gives you:

    ['mike\tjohn\tsteve']        # no spaces, all in one column
    ['mike', 'john', 'steve']    # multiple consecutive spaces = 1 column-divider