Reading data to python: turn into list or dataframe - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Reading data to python: turn into list or dataframe (/thread-33842.html) |
Reading data to python: turn into list or dataframe - hhchenfx - Jun-01-2021 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) RE: Reading data to python: turn into list or dataframe - perfringo - Jun-01-2021 This is fileobject RE: Reading data to python: turn into list or dataframe - Larz60+ - Jun-01-2021 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. |