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:
Table:
|order-id |order-item-id |purchase-date |payments-date| |-----------|---------------|---------------|-------------| |701-0760362-5416244 |53183430145170 |2022-06-25T15:16:44 00:00 |2022-06-25T15:16:44 00:00| |701-2211906-0172215 |57327029496858 |2022-06-25T15:58:01 00:00 |2022-06-25T15:58:01 00:00| |701-5211711-8876233 |57354763629402 |2022-06-25T19:02:34 00:00 |2022-06-25T19:02:34 00:00| 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-0760362-5416244 53183430145170 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 Jardim 000000132046310000 Fogão Brastemp 5 Bocas De Embutir Cor Inox Com Mesa De Vidro 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 Unidas 111 Apartamento 11 Cidade Jardim São José dos Josés PR 11135111 BR false
CodePudding user response:
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')
CodePudding user response:
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")