首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >你好,帮助我使用txt.in PLease

你好,帮助我使用txt.in PLease
EN

Stack Overflow用户
提问于 2021-01-20 03:58:27
回答 1查看 53关注 0票数 1

我必须在python 2中写一个txt.files是数字的输入:写在2行4-1和12-3中我必须做减法并将结果写到其他txt.file中

请帮帮我,我对python非常陌生,刚刚开始学习它。提前感谢你们所有人

这是我一直写到现在的内容:

代码语言:javascript
复制
    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这一定是结果

EN

回答 1

Stack Overflow用户

发布于 2021-01-20 04:32:35

这是一个Python 2.7解决方案:

代码语言:javascript
复制
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的过程中一切顺利:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65798624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档