How to calculate txt data with python code?

Viewed 35

I have a long column data from txt file. I want to make a calculation with this txt file and save the result in the txt file? What should I do? For example:

1

2

3

4

5

The answer should be: (*3)

3

6

9

12

15

3 Answers

The simple answer is to use the open() function on the file to create a file object, then use the file object's readlines() function to get a list of strings, each string being a line in the file. Then you can sum the list of integers and use the write function to append it as a line. Something like this.

with open(filepath) as file:
    lines = file.readlines()
    linesAsIntegers = [int(x) for x in lines]
    sumOfLines = str(sum(linesAsIntegers))
    file.write('\n'+sumOfLines)
    

A way you could do it is by opening the file and computing the str version of the numbers multiplied by three (with \n at the end), then writing them into the file:

with open("f.txt") as file:
    results = [str(int(num.strip()) * 3) + "\n" for num in file.readlines()]
with open("f.txt", "w") as file:
    file.writelines(results)

you can do it like this:

FileHasNumbers = open("ThatFile.txt","r")
Numbers = FileHasNumbers.readlines()
FileHasNumbers.close()

NewResult = ""

for i in Numbers:
    NewResult += "{}\n".format(int(i.split("\n")[0]) * 3)

FileHasNumbers = open("ThatFile.txt","w")
FileHasNumbers.write(NewResult)
FileHasNumbers.close()
Related