Reputation: 21
I have this file with a list of fractions and I want to simplify them. The list is written like follows:
124/246
71/69
2574/3850
...
In order to simplify im trying to extract numerator and denominator with the following code but it only seems to be extracting the last digits(f1 and f2 are my opened files where I read and write, and Simplify is a previously defined function):
while f1.readline() != "":
i = 1
while f1.read(1) != "/":
num = f1.read(i)
i += 1
den = f1.read(i)
num, den = Simplify(int(num), int(den))
f2.write(str(num) + "/" + str(den) + "\n")
I would appriciate some guidance. Thanks a lot :)
Upvotes: 1
Views: 1169
Reputation: 781004
You're making this much more complicated than necessary, and in the process doing lots of things wrong.
When you call f1.readline()
or f1.read(1)
in an if
condition, it consumes that line or character from the file. The next file operation will read from where it left off, it won't go back and process the same line again. So unless you save the file position (with f1.tell()
) and then go back to it (with f1.seek()
), you can't use this pattern to count the number of characters before the /
and then read them again.
But there's no need to count anything. Just read the line and use split()
to separate it into numerator and denominator.
for line in f1:
line = line.strip() # remove newline
num, den = line.split('/')
num, den = Simplify(int(num), int(den))
f2.write(str(num) + "/" + str(den) + "\n")
Upvotes: 3
Reputation: 442
I would approach this a different way.
First, I would get every line from f1 and store it in a list. Then, I would loop through this list and use the split()
function to get the numerator and denominator. Finally, I'd write them to f2.
Here is some code that would do that:
lines = f1.readlines() # Store all the lines in a list
for fraction in lines:
split_fraction = fraction.split("/") # Split the fraction into a list containing the numerator and denominator
num = split_fraction[0]
den = split_fraction[1]
num, den = Simplify(int(num), int(den))
f2.write(str(num) + "/" + str(den) + "\n")
Upvotes: 1