I have an input file, which contains lines like ' 6 5' (operator, four spaces, integer, four spaces, integer). I need to make an output file, which contains results of an operation (from ' 6 5' to '11'). All results should be separated by ','. How can make it elegantly not to add ',' in the last iteration of the loop (without moving the last iteration out of the loop)?
Thank you!
output = open("/Users/aleksandrdudakov/Downloads/output_file.txt", "w")
data = input.readlines()
for i in range(len(data) - 1):
s = data[i]
l = s.split(sep=' ')
if l[0] == ' ':
output.write(str(int(l[1]) int(l[2])))
if l[0] == '-':
output.write(str(int(l[1]) - int(l[2])))
if l[0] == '*':
output.write(str(int(l[1]) * int(l[2])))
if l[0] == '//':
output.write(str(int(l[1]) // int(l[2])))
if l[0] == '%':
output.write(str(int(l[1]) % int(l[2])))
if l[0] == '**':
output.write(str(int(l[1]) ** int(l[2])))
output.write(',')
i = 1
s = data[i]
l = s.split(sep=' ')
output.write(str(int(l[1]) // int(l[2])))
input.close()
output.close()```
CodePudding user response:
As DrakeLiam mentions, you can either add a check of whether you're at the beginning of the loop and skip prepending the comma, or add a check of whether you're at the end of the loop and skip appending the comma.
output = open("/Users/aleksandrdudakov/Downloads/output_file.txt", "w")
data = input.readlines()
for i in range(len(data)):
if i > 0:
output.write(',')
s = data[i]
l = s.split(sep=' ')
if l[0] == ' ':
output.write(str(int(l[1]) int(l[2])))
if l[0] == '-':
output.write(str(int(l[1]) - int(l[2])))
if l[0] == '*':
output.write(str(int(l[1]) * int(l[2])))
if l[0] == '//':
output.write(str(int(l[1]) // int(l[2])))
if l[0] == '%':
output.write(str(int(l[1]) % int(l[2])))
if l[0] == '**':
output.write(str(int(l[1]) ** int(l[2])))
input.close()
output.close()
CodePudding user response:
An alternative is to use print
with parameter sep
(and file
):
def calc(line):
op, x, y = line.rstrip('\n').split()
x, y = int(x), int(y)
output = 'error' # default; if no pattern is matched, this will be printed
if op == ' ': output = x y # or, match .. case for python 3.10
if op == '-': output = x - y
if op == '*': output = x * y
if op == '//': output = x // y
if op == '**': output = x ** y
return str(output)
with open("test.txt", "r") as f, open("output.txt", "w") as g:
print(*map(calc, f), sep=',', file=g)
test.txt
:
1 2
* 2 3
// 4 2
? 1 1
** 2 3
output.txt
:
3,6,2,error,8