我必须在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这一定是结果
发布于 2021-01-20 04:32:35
这是一个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的过程中一切顺利:)
https://stackoverflow.com/questions/65798624
复制相似问题