Likonen
Likonen

Reputation: 29

Appending txt data in pandas

I'm trying to append data from a txt file that looks like this:

Kit Kat|2 packets |Candy| 6
Flour|1 book|Book|2

I am trying to create a pandas DataFrame from this txt file with the column names: name, quantity, category, ID.

This is the code im currently using:

import pandas as pd

df = pd.DataFrame(columns=['Name', 'Quantity', 'Category', 'ID'])

file = open("food.txt", "r")

for line in file:
   fields = line.split("|")
   product = df.append({'Name': fields[0]}, ignore_index=True)
   qty = df.append({'Quantity': fields[1]}, ignore_index=True)
   category= df.append({'Category': fields[2]}, ignore_index=True)
   ID = df.append({'ID': fields[3]}, ignore_index=True)

df.head()

I am getting an empty dataframe as a result, anyone knows why?

Upvotes: 1

Views: 1890

Answers (1)

bcosta12
bcosta12

Reputation: 2452

Just use read_csv with sep='|' and names=[COLUMNS_NAME]

import pandas as pd

columns_name = ['Name', 'Quantity', 'Category', 'ID']
df = pd.read_csv('file.txt', sep='|', names=columns_name)

print(df)

file.txt

Kit Kat|2 packets |Candy| 6
Flour|1 book|Book|2

result:

enter image description here

Upvotes: 7

Related Questions