问题描述
必须在python 2 txt.files中写入一个是数字输入:在2行4-1和12-3中写入我必须进行减法并将结果写入其他txt.file
请帮帮我我对python很菜,刚开始学习。 先谢谢大家
这就是我到现在为止设法写的:
import calculator
with open ('./expresii.txt','r') as f:
line = f.readlines()
for l in line:
if l[1] == '-':
print(calculator.subtraction(int(l[0]),int(l[2])))
else:
print(calculator.addition(int(l[0]),int(l[2])))
with open ('./expresii.txt','r') as f2:
print(f2.read())
首先我得到数字的减法 从第二个我得到必须减去的数字
现在如何写入新文件 4-1=3 和 12-3=9 这一定是结果
解决方法
这是一个 Python 2.7 解决方案:
import re
# opens the input file in readmode
with open ('expresii.txt','r') as f:
# creates an iterable of the lines in the file
lines = f.readlines()
# create an empty array which will store the data to write to the output file
to_file = []
# loops through every line in the file
for l in lines:
# creates a list of ints of all the numbers in that line
nums = list(map(int,re.findall(r'\d+',l)))
# calculate the result by subtracting the two numbers
result = nums[0] - nums[1]
# append answer (e.g 4-1=3) to a list,that will later be written to a file
line = str(nums[0])+'-'+str(nums[1])+'='+str(result)+'\n'
to_file.append(line)
#open the output file in write mode
with open('output_file.txt','w') as f:
# write the to_file list to output_file.txt
f.writelines(to_file)
此解决方案在文件的每一行中查找所有数字,并在您减去它们时计算结果。在为输入文件中的每一行完成此操作后,它会将这些数据写入输出文件。
祝你继续学习 Python :)