Doing calculation with ascii file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Doing calculation with ascii file (/thread-21499.html) |
Doing calculation with ascii file - Mike - Oct-02-2019 Hello! I have file named DATA.TXT which contains: I am trying to read this in using line-by-line (for learning purpose), then add new column with sum on first two number. So that when I save the new file, I get: And so far I am using this code:f = open('DATA.TXT', 'r') next(f) for line in f: print(line), f.close() RE: Doing calculation with ascii file - snippsat - Oct-02-2019 To take a little further,and is better to use with open() then don't need to use close() as it dos automatically.with open('col.txt') as f: next(f) for line in f: line = line.strip() num1, num2 = line.split(',') num1, num2 = int(num1), int(num2)So now is ready to continue further,if i do a test after running this code. >>> num1 + num2 803As expected i get the last calculation. RE: Doing calculation with ascii file - Mike - Oct-02-2019 Thank you! Tried Your solution and it works. Added lines: num3 = num1 + num2 print(num1,num2,num3)Which gives the first row: Now somehow have to append (?) it and use FOR cycle to loop every row or do "next i" like in Excel VBA.
RE: Doing calculation with ascii file - Mike - Oct-02-2019 I guess I solved my problem. Here is the script: with open('file.txt',"r") as in_file, open('file2.txt',"w") as out_file: next(in_file) for line in in_file: line = line.strip() num1, num2 = line.split(',') num1, num2 = int(num1), int(num2) num3 = num1 + num2 out_file.write(str(num1) + "," + str(num2) + "," + str(num3) + "\n") continueWhich outputs external file "file2.txt", although without headers that I removed using command "next(in_file)"
RE: Doing calculation with ascii file - snippsat - Oct-02-2019 Yes can do it like this. Here an other version you can look at using f-string .Also put in header line just as a example. See that with string formatting(f-string) it look better no need for str() or + .with open('col.txt') as f,open('total.txt', 'w') as f_out: header = next(f) c1, c2 = header.strip().split(',') f_out.write(f'{c1} {c2} Sum\n') for line in f: line = line.strip() num1, num2 = line.split(',') num1, num2 = int(num1), int(num2) num3 = num1 + num2 f_out.write(f'{num1} + {num2} ${num3}\n')
RE: Doing calculation with ascii file - Mike - Oct-02-2019 Thanks! Although a bit confusing is the header separating-adding thing. |