r/backtickbot • • Mar 30 '21

https://np.reddit.com/r/pythonhelp/comments/mg4fs6/need_to_convert_decimals_into_integers_that_are/gsrqroh/

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 to 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, thento integer and string afterwards. This is useless, as everything read from a file is string. Also, why are you using backslash in new_line?

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?

# Open input.txt and read its lines:
f = open("input.txt").readlines()

# Open output.txt for writing:
fout = open("output.txt", "w")

# For each line in input.txt
for line in f:

    # l is now a list of all the numbers from input.txt:
    l = line.split(",")

    # For each number in the list:
    for item in l:
        # new_line is the number, with a comma after:
        new_line = item + ","
        # write the new_line to the file
        fout.write(new_line)

# After reading -> writing is done, close both files
# to not stress RAM. In your case, you might not
# need this as the files are closed as soon as the
# program terminates, but this is a good practice
# for larger applications.

fout.close()
f.close()
1 Upvotes

0 comments sorted by