Search code examples
pythontext-filesdelimiteropenrowsetstructured-data

Read n qty rows of delimited txt file in Python


I have a large txt file that I want to read in python. It's tab delimited. I want to be able to read the headers as well. I saw this stackoverflow site but it doesn't show how to both designate the n qty of rows as well as determine the delimiter and line break: Read first N lines of a file in python


Solution

  • Pandas dataframe will help you do that automatically.

    import pandas as pd
    df = pd.read_csv(myfile,sep='\t')
    df.head(n=5)  # for the 5 first lines of your file
    

    For more info, see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html#pandas.read_csv