I have an XLSX file which I am using python to convert to CSV to allow me to manipulate using pandas, I would then like to export the data from the CSV file into a formatted text document.
The xlsx data is as follows
Name | Number | Branch Manager |
---|---|---|
Gustavo Barrett | 45 | Avery Page |
Sterling Lynn | 199 | Matteo Hicks |
I would like the format to be as follows for the TXT file
*****NEW RECORD*****
Name : Gustavo Barrett
Number : 45
Branch Manager : Avery Page
*****RECORD END*****
*****NEW RECORD*****
Name : Sterling Lynn
Number : 199
Branch Manager : Matteo Hicks
*****RECORD END*****
Below is my current code which prints all the names first, then the numbers and the branch managers, it prints them all separately, any idea how i can get it to output in the format i want?
import pandas as pd
from pandas import DataFrame
import time
with open("waffles.txt", "w") as file:
filename = 'finals.xlsx'
df = pd.DataFrame(pd.read_excel(filename))
names = df["Name"].to_list()
numbers = df["Number"].to_list()
branch = df["Branch Manager"].to_list()
for i in names:
for i in names:
txt_name = "Name : "+str(i)
for o in numbers:
txt_number = "Number : "+str(o)
for a in branch:
txt_branch = "Branch Manager : "+str(a)
file.write("\n")
file.write("*****NEW RECORD*****")
file.write("\n")
file.write(i+ "\n")
file.write(str(o)+ "\n")
file.write(a+ "\n")
file.write("*****RECORD END*****")
file.write("\n")
Is there some sorting problem or what ... you have more for loops then you need.
This should work, with tweaks. I would suggest to read on some basic string formatting in Python.
import pandas as pd
with open("waffles.txt", "w") as file:
filename = 'finals.xlsx'
df = pd.read_excel(filename)
for index, row in df.iterrows():
file.write("\n*****NEW RECORD*****\n")
# Adjust it with csv column names
file.write(f"Name : {row['name']}\n")
file.write(f"Number : {row['number']}\n")
file.write(f"Branch Manager : {row['branch manager']}\n")
file.write("*****RECORD END*****\n")