Sandrocottus
Sandrocottus

Reputation: 533

Python: Splitting a string by delimiter and writing to columns in excel file

I have a text file with the following hex string:-

ffffe7ba2cffffe7c52cffffe7c22cffffe7c12cffffe7c82cffffe7c62cffffe7b52cffffe7a02c

I want to split this string by the delimiter 2c (which appears in the string after every 8 characters).

Then I want to store the sub-strings in a column in an excel file, so the excel file would look like:-

Excel

So far I am able to open the text file, read the data, split it by the delimiter 2c, and write it vertically to the excel file using the following (shabby) code:-

    with open(inputfilename, 'r') as myfile:
        string1 = myfile.readline()

    string2 = ((str((string1).split("2c"))).replace("'", ""))

    with open(outputfilename, "a+") as myfile1:
        myfile1.write(string2)

Please suggest how can I split the string and write the sub-strings to a column in excel file efficiently.

Thanks in advance!

Edit 1:

Almost got it with:-

with open(inputfilename, 'r') as text_file, open(outputfilename, 'a') as myfile:  
    for line in text_file:
        string1 = str(line.split("2c"))
        string2 = string1.replace("'", "")
        myfile.write("%s" %string2)
        myfile.write("\n")

except that the "\n" doesn't write the value to a newline in the excel file.

I have even opened the excel file with "a" access mode, however still writing the values vertically. Any suggestions?

Upvotes: 0

Views: 2918

Answers (1)

L3viathan
L3viathan

Reputation: 27283

As I warned in a comment, your seperators are probably the byte 2c, not the string "2c". It is probably easier to just split every 8 characters:

with open(inputfilename, 'r') as myfile:
    string1 = myfile.readline().strip().strip("'")  # get rid of quotes

with open(outputfilename, "a+") as myfile1:
    myfile1.write(",".join(
        string1[i:i+8] for i in range(0, len(string1), 10)
    ))

Upvotes: 1

Related Questions