Python Forum

Full Version: Reading data to python: turn into list or dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I tried 3 different ways to read csv data into python.

The 1st and 2nd methods turn data to dataframe and list, and they both work OK

The 3rd method, return something with:

type(dt): <class '_io.TextIOWrapper'>

print(dt): <_io.TextIOWrapper name='C:\\temp\\LongPctls.csv' mode='r' encoding='cp1252'>

Can you please help explain what form of data is that?

When I use for loop, I can still print out dt.

Thank you, Hong
#Method 1: return dataframe
    file_name_csv="C:\\temp\LongPctls.csv"
    df=pd.read_csv(file_name_csv)
    print(type(df))
    print(df)

 #Method 2: return list
    file = "C:\\temp\LongPctls.csv"
    data = open(file, "r")
    list = data.read().split('\n')
    print(list)
    print(type(list))
    
# Method 3: ?????
    with open("C:\\temp\LongPctls.csv",  mode="r") as dt:
            print(type(dt))
            print(dt)
            for i in dt:
                print(i)
This is fileobject
You can also use:
with open("C:\\temp\LongPctls.csv") as fp:
    crdr = csv.reader(fp) # can add optional [inline]delimiter='.'[/inline] if not comma (replace . with delimiter)
    for row in crdr:
        print(f"type row: {type(row)}, row: {row}"
Using this method , if there is a header, it will be the first row

Or, if you prefer a dictionary, use:
with open("C:\\temp\LongPctls.csv") as fp:
    crdr = csv.DictReader(fp) # can add optional [inline]delimiter='.'[/inline] if not comma (replace . with delimiter)
    for row in crdr:
        print(f"type row: {type(row)}, row: {row}"
Each row will be a dictionary.