Sandrocottus
Sandrocottus

Reputation: 533

Convert and concatenate data from two columns of a csv file

I have a csv file which contains data in two columns, as follows:

  1. 40500 38921
  2. 43782 32768
  3. 55136 49651
  4. 63451 60669
  5. 50550 36700
  6. 61651 34321

and so on...

I want to convert each data into it's hex equivalent, then concatenate them, and write them into a column in another csv file.

For example: hex(40500) = 9E34, and hex(38921) = 9809. So, in output csv file, element A1 would be 9E349809

So, i am expecting column A in output csv file to be:

  1. 9E349809
  2. AB068000
  3. D760C1F3
  4. F7DBECFD
  5. C5768F5C
  6. F0D38611

I referred a sample code which concatenates two columns, but am struggling with the converting them to hex and then concatenating them. Following is the code:-

import csv

inputFile = 'input.csv'
outputFile = 'output.csv'

with open(inputFile) as f:
    reader = csv.reader(f)
    with open(outputFile, 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [''.join([row[0], row[1]])] + row[2:]
            writer.writerow(new_row)

How can i convert data in each column to its hex equivalent, then concatenate them and write them in another file?

Upvotes: 0

Views: 146

Answers (2)

ParvBanks
ParvBanks

Reputation: 1436

You could do this in 4 steps:

  1. Read the lines from the input csv file

  2. Use formatting options to get the hex values of each number

  3. Perform string concatenation to get your result

  4. Write to new csv file.

Sample Code:

with open (outputFile, 'w') as outfile:
    with open (inputFile,'r') as infile:
        for line in infile:             # Iterate through each line
            left, right = int(line.split()[0]), int(line.split()[1]) # split left and right blocks
            newstr = '{:x}'.format(left)+'{:x}'.format(right) # create new string using hex values excluding '0x'
            outfile.write(newstr)   # write to output file
    print ('Conversion completed')
print ('Closing outputfile')

Sample Output:

In[44] line = '40500 38921'
Out[50]: '9e349809'

Upvotes: 2

olinox14
olinox14

Reputation: 6662

ParvBanks solution is good (clear and functionnal), I would simplify it a little like that:

with open (inputFile,'r') as infile, open (outputFile, 'w+') as outfile:
    for line in infile:
        outfile.write("".join(["{:x}".format(int(v)) for v in line.split()]))

Upvotes: 2

Related Questions