Reputation:
I have this .txt file that has a table/dataframe, I would like to convert it to .csv in Python, could you help me? (sorry for any mistakes in my question)
Image:
Full column example:
order-id order-item-id purchase-date payments-date buyer-email buyer-name payment-method-details cpf ship-county buyer-phone-number sku product-name quantity-purchased currency item-price item-tax shipping-price shipping-tax ship-service-level recipient-name ship-address-1 ship-address-2 ship-address-3 ship-city ship-state ship-postal-code ship-country ship-phone-number delivery-start-date delivery-end-date delivery-time-zone delivery-Instructions is-business-order purchase-order-number price-designation
701-0760000-5410044 00083400045170 2022-06-25T15:16:44+00:00 2022-06-25T15:16:44+00:00 [email protected] Everton Everton da Everton Other 000.000.000-01 Cidade Cidade 000000132046310000 Fogão Fogão 5 Bocas De Fogão Cor Inox Com Mesa De Fogão E Touch Timer Com Autodesligamento - 0YS5000 110V 1 BRL 1119.00 0.00 101.90 0.00 Standard Everton Everton da Everton Rua das Ruas Ruas 111 Apartamento 11 Cidade Cidade São José dos Josés PR 11135111 BR false
Upvotes: 2
Views: 4116
Reputation: 39
You can use pandas to open it:
import pandas as pd
text_file = pd.read_table('file_name.txt')
And write it as a csv:
text_file.to_csv('new_file_name.csv')
Upvotes: 1
Reputation: 515
This is if you don't want to use other packages such as pandas, this is the 'manual' way to go about creating a CSV from a TXT. I am assuming that you have tab characters as separators in your text file. If this is not the case, then you will need to change this line:
values = line.strip("\n").split("\t") # split on tab character
The "\t" represents the character that separates the columns.
This block of code will take your text file and convert it to a csv file. Put this in a python file in the same folder as your .txt file.
filename = "table.txt" # name of your file, this is probably different on your end!
rows = []
with open(filename, "r") as f:
for line in f.readlines():
values = line.strip("\n").split("\t") # split on tab character
rows.append(values)
print(rows)
with open("my_file.csv", "w") as f:
for row in rows:
for i, element in enumerate(row):
f.write(f"{element}")
if i != len(row)-1:
f.write(",")
else:
f.write("\n")
Upvotes: 0