Hello all I have a text document that has two sets of numbers 4-1 and 9-3 code need to read them and write in a same text document and need to watch out for newline then the code need to calculate them and print without entry tnx all for help
I have tried
f = open("Odin.txt","r")
print(f.read())
f.close()
f = open("Odin.txt","w")
for f in line:
res = eval(line.strip())
output.write(line.strip()+"="+str(res)+"\n")
f.close()
f = open("Odin.txt","r")
print(f.readline(),end="")
print(f.readline(),end="")
f.close()
Your option 1 is close, but your for f in line
is backwards; you wanted for line in f
(i.e. iterate over each line
in the f
ile). It's also easier if you read the whole file in before you start writing out the modified version.
# Read a copy of the file into memory as a list.
with open("Odin.txt") as f:
lines = list(map(str.strip, f.readlines()))
# Write out the new content.
with open("Odin.txt", "w") as f:
for line in lines:
f.write(f"{line}={eval(line)}\n")
>cat Odin.txt
4-1
9-3
>python odin.py
>cat Odin.txt
4-1=3
9-3=6