[英]Hello, I am new to python and I am having difficulties on having a file as an input. Can somebody help me please?
[英]hello,PLease help me with txt.in Python
必须写入 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)
此解决方案在文件的每一行中查找所有数字,并在减去它们时计算结果。 在对输入文件中的每一行执行此操作后,它会将这些数据写入 output 文件。
祝你继续学习Python:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.