简体   繁体   中英

hello,PLease help me with txt.in Python

have to write in python 2 txt.files one is input of numbers: writen in 2 lines 4-1 and 12-3 I have to make the subtraction and write the result to other txt.file

please help me I am very green to python, just started to learn it. Thanks you all in advance

this is what I managed to write till now:

    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())

in first I get the subtraction of numbers and from the second I get the numbers that must be subtrated

now how do I write toa new file 4-1=3 and 12-3=9 this must be the result

Here is a Python 2.7 Solution:

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)

This solution finds all of the numbers, in each line of the file, and calculates the result when you subtract them. After it has done this for every line in the input file, it then writes this data to an output file.

I wish you well as you continue to learn Python:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM