Search code examples
pythonreadfile

How can I read specific colums from a txt file in python?


I have a .txt dataset like this:

user_000044 2009-04-24  13:47:07    Spandau Ballet  Through The Barricades 

I have to read the last two colums, Spandau Ballet as unique and Through the Barricades as unique. How can I do this?

In need to create two array, artists =[] and tracks = [] in which I put data in a loop, but I can't define the portion of text in a line.

Someone can help me?


Solution

  • You are probably better off with using the pandas-module to load the content of the .txt into a pandas DataFrame and proceed from there. If you're unfamiliar with it...a DataFrame is as close to an Excelsheet as it can get with Python. pandas will handle reading the lines for you so you don't have to write your own loop.

    Assuming your textfile is four column, tab-separated, this would look like:

    # IPython for demo:
    import pandas as pd
    
    df = pd.read_csv('ballet.txt', sep='\t', header=None, names=['artists', 'tracks'], usecols=[2, 3])
    # usecols here limits the Dataframe to only consist the 3rd and 4th column of your .txt
    

    Your DataFrame then could look like:

    df
    # Out: 
              artists                  tracks
    0  Spandau Ballet  Through The Barricades
    1   Berlin Ballet               Swan Lake
    

    Access single columns by column names:

    df.artists  # or by their index e.g. df.iloc[:, 0]
    # Out: 
    0    Spandau Ballet
    1     Berlin Ballet
    Name: 2, dtype: object
    

    You can still put the data into an array at this point, but I can't think of a reason you really wanna do this if you're aware of the alternatives.