【发布时间】:2018-05-16 17:16:59
【问题描述】:
我目前正在尝试编写一个代码,该代码接受用户的输入,要求他们打开一个包含数学问题的文件,然后输出一个包含这些问题答案的文件。我已经到处寻找某种解决方案,但这些是我得到的最接近的:
文本文件内容:
2 + 2
3 * 3
4.5 - 2.3
-8.8 + 1.2
2 ^ 4
8.9 / 2.3
5 % 3
-2 * -2
尝试 1:
input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")
with open(input_file_name,"r") as input_file:
contents = input_file.readlines()
num = "".join(contents)
contents_length = len(num)
with open(output_file_name, "w") as output_file:
while contents_length >= 0:
num = num.replace("^","**") # change the ^ to ** so python can properly do the function
contents_value = exec(num)
contents_length = contents_length - 1
output_file.write(str(contents_value))
我收到的文本文件会返回“无”
尝试 2:
input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")
infile = open(input_file_name, "r")
outfile = open(output_file_name, "w")
lines = infile.readlines()
i = len(lines) - 1
while i >= 0:
ans = eval(lines[i])
outfile.write(str(ans))
i = i - 1
infile.close()
outfile.close()
并且文本文件中有 423.86956521739130476-7.60000000000000052.294 在文件中。
所以,我真的不确定还能做什么。任何帮助将不胜感激。
【问题讨论】:
标签: python string file math text