i have two files containing lists and I would like to perform some manipulations with the numbers.

file 1:

  • A 1

  • B 2

  • C 3

and file 2:

  • A 4

  • B 5

  • C 6

I have written the following code to read in the files and then add list 1 and list 2 together. The code is as follows:

energy_file_in= open('test.dat', "r")
slab_file_in= open('pt3x_slab.dat', "r")
energy_in=energy_file_in.readlines()
slab_in=slab_file_in.readlines()
energy_file_in.close()
slab_file_in.close()

#write data
raw_data_1_file_out = open('ads_ene.dat', "w")

energy=[]
for i in energy_in:
    energy=i.split()
    for j in slab_in:
        slab=j.split()
        x = "%0.7f" %(float(float(energy[1]))+(float(slab[1])))
        print>>raw_data_1_file_out,slab[0], x

The output it generates is not what I want. I just want it to generate a list showing

A 5
B 7
C 9

Pls can someone suggest where I am going wrong with this code.

Thank you

Dani AI

Generated

The problem is the nested loop: every energy line is being added to every slab line, producing a cartesian product instead of one-to-one sums. was right to say the records must be processed in parallel, and correctly flagged the loop mistake (you can’t iterate an integer). Blank lines in the HTML listing suggest the input may contain empty lines too, so skip those when parsing.

If the two files are the same length and corresponding lines match, process them in parallel (example uses Python 3 style context managers):

with open('test.dat') as f1, open('pt3x_slab.dat') as f2, open('ads_ene.dat', 'w') as out:
    for l1, l2 in zip(f1, f2):
        p1 = l1.split()
        p2 = l2.split()
        if len(p1) < 2 or len(p2) < 2:
            continue
        if p1[0] != p2[0]:
            # handle label mismatch as needed
            continue
        total = float(p1[1]) + float(p2[1])
        out.write("{} {:0.7f}\n".format(p1[0], total))

If the files might be unordered or have repeated labels, build totals by key:

from collections import defaultdict

tot = defaultdict(float)
for path in ('test.dat', 'pt3x_slab.dat'):
    with open(path) as f:
        for line in f:
            parts = line.split()
            if len(parts) < 2:
                continue
            tot[parts[0]] += float(parts[1])

with open('ads_ene.dat', 'w') as out:
    for key in sorted(tot):
        out.write("{} {:0.7f}\n".format(key, tot[key]))

Troubleshooting tips: trim whitespace with line.strip() or parts = line.split() and if not parts: continue; use itertools.zip_longest if lengths differ and missing values must be handled; avoid Python 2 print >> syntax and prefer context managers for file I/O.

Recommended Answers

All 5 Replies

Assuming both files are the same length (if they are not you will have to account for that), use the same offset for each list, i.e. record 1 from file a-->record 1 from file b

for ctr in len(energy_in):
    ## print them for testing
    print energy_in[ctr], slab_in[ctr]
    energy=energy_in[ctr].split()
    ##for j in slab_in:
    slab=slab_in[ctr].split()

    if energy[0] == slab[0]:
        x = "%0.7f" % (float(energy[1])+float(slab[1]))
    else:
        print "Recs not equal", energy, slab

If you want to find all "A"s and add them together, and the files do not correspond, then you should use a dictionary.

Pls can someone

Please don't turn this forum into a high school.

Member Avatar for Member #912166

Assuming both files are the same length (if they are not you will have to account for that), use the same offset for each list, i.e. record 1 from file a-->record 1 from file b

for ctr in len(energy_in):
    ## print them for testing
    print energy_in[ctr], slab_in[ctr]
    energy=energy_in[ctr].split()
    ##for j in slab_in:
    slab=slab_in[ctr].split()

    if energy[0] == slab[0]:
        x = "%0.7f" % (float(energy[1])+float(slab[1]))
    else:
        print "Recs not equal", energy, slab

If you want to find all "A"s and add them together, and the files do not correspond, then you should use a dictionary. Please don't turn this forum into a high school.

You can't iterate over an integer ;)

@OP, your post doesn't really explain your code, nor provide good examples of input/output. If you want better help, you're going to need to try and write a better description of what you want to happen, what you have to make that happen and what you're not understanding.

The code the OP posted creates lists

energy_in=energy_file_in.readlines()
slab_in=slab_file_in.readlines()

Member Avatar for Member #912166

The code the OP posted creates lists

I'm referring to

for ctr in len(energy_in):

;)

Too late to change it now. I have no problems with the OP doing a little debugging anyway, and since this post was in many forums, probably someone else has already provided enough to answer the OP's question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.