When you call read()
you are getting back the entire contents of the file. The text of the numbers and the newline characters. To process each number (one per line) you would want to split op
on the newline character "\n"
.
Something like:
with open("in.txt", "r") as file_in:
for row in file_in.read().split("\n"):
print(int(row) / 2)
Note that split()
would also be valid as the default behavior is split()
to do so on whitespace including line breaks and tabs.
However, this is such a common thing python allows one to simplify this to:
with open("in.txt", "r") as file_in:
for row in file_in:
print(int(row) / 2)
Either will give you back:
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
Addendum:
Per the OP, the use of readlines()
also fits the bill here and I will pull their comment into this answer for clarity.
with open("in.txt") as file_in:
for row in file_in.readlines():
print(int(row) / 2)