In: Computer Science
2. Combine multiple files
Use Python programming to combine two text files: customer-status.txt and sales.txt
Data columns in customer-status.txt (separated by comma):
Account Number, Name, Status 527099,Sanford and Sons,bronze
Data columns in sales.txt (separated by comma):
Account Number, Name, SKU, Quantity, Unit Price, Ext Price, Date
163416,Purdy-Kunde,S1-30248,19,65.03,1235.57,2014-03-01 16:07:40 527099,Sanford and Sons,S2-82423,3,76.21,228.63,2014-03-01 17:18:01
After you combine, you will see the following:
527099,Sanford and Sons,S2-82423,3,76.21,228.63,2014-03-01 17:18:01,bronze
Here is the code :
note : put the customer-status.txt and sales.txt in the same folder as the python file
import re
customer_status = open("customer-status.txt", "r")
cust_arr=[]
sales_arr=[]
new_file_arr=[]
for line in customer_status:
temp=[]
line=line.split(',');
for sub in line:
temp.append(re.sub('\n','',sub))
cust_arr.append(temp);
customer_status.close()
sales=open("sales.txt","r")
for line in sales:
temp=[]
line=line.split(',');
for sub in line:
temp.append(re.sub('\n','',sub))
sales_arr.append(temp);
sales.close();
for i in range(1,len(cust_arr)):
for j in range(1,len(sales_arr)):
if cust_arr[i][0]==sales_arr[j][0]:
sales_arr[j].append(cust_arr[i][2])
new_file_arr.append(sales_arr[j])
new_file_str="";
for line in new_file_arr:
for word in line:
new_file_str=new_file_str+word+','
new_file_str=new_file_str+'\n'
print(new_file_str)
new_file = open('output.txt', 'w')
new_file.write(new_file_str)
new_file.close()