r/pythonhelp • u/TDA_Alex • Mar 30 '21
HOMEWORK Need to convert decimals into integers that are separated by commas
I have been stuck on a homework assignment where we need to read a dataset into python code supplied by my teacher. problem is, his code does not like decimals and refuses to give proper data without integers. Having virtually no experience with python, I had to probe him in order to get this code:
f=open("input.txt",).readlines()
fout=open("output.txt","w")
for line in f:
l = line.split(",")
for item in l:
number = float(item)
new_line = str(int(number)) + ","fout.write(new_line)fout.close()
Problem is, this code seems to only read the values at the end of each line (which are whole numbers) and writes only those to the output file. Further, the formatting is wrong, since they are in rows but just one long line. suffice to say I am terribly confused, and would appreciate any and all help. For reference, here is a sample of the file:
3.6216,8.6661,-2.8073,-0.44699,1
4.5459,8.1674,-2.4586,-1.4621,1
3.866,-2.6383,1.9242,0.10645,1
3.4566,9.5228,-4.0112,-3.5944,1
0.32924,-4.4552,4.5718,-0.9888,1
4.3684,9.6718,-3.9606,-3.1625,1
3.5912,3.0129,0.72888,0.56421,1
2.0922,-6.81,8.4636,-0.60216,1
3.2032,5.7588,-0.75345,-0.61251,1
1.5356,9.1772,-2.2718,-0.73535,1
and this is the output I get:
1,1,1,1,1,1,1,1,1,1,
1
u/xCustomWorld Mar 30 '21 edited Mar 30 '21
I don't understand what's exactly your goal. You have a text file with decimal numbers separated by commas and you need to convert them into integers separated with commas and write that to file?
Despite your code being formatted wrong, I can see that you are converting the read string from input.txt to float, then to integer and string afterwards. This is useless, as everything read from a file is string. Also, why are you using backslash in
new_line?Your problem is with the conversions I think. Integers cannot be floats/decimals and they're skipped because the conversion fails. Then you're left with only
1s, as these can be integers.I'm on mobile, but this should work. If you want, I can look at it in VSCode on PC later, if you still need it. But I am still out of context with your goal, could you specify it please?