我有两组数字4-1和9-3代码的文本文档,它们需要在相同的文本文档中读取和写入,并且需要小心换行符,然后需要计算它们并打印,而不用输入作为选项2 tnx的帮助。
我已经尝试了选择1
f = open("Odin.txt","r")
print(f.read())
f.close()
f = open("Odin.txt","w")
for f in line:
res = eval(line.strip())
output.write(line.strip()+"="+str(res)+"\n")
f.close()
f = open("Odin.txt","r")
print(f.readline(),end="")
print(f.readline(),end="")
f.close()
我试着选择2
f = open("Odin.txt","r")
print(f.readline(),end="")
print(f.readline())
f.close()
f = open("Odin.txt","w")
a = 4-1
b = 9-3
f.write(f"4-1 = {a}\n")
f.write(f"9-3 = {b}\n")
f.close()
f = open("Odin.txt","r")
print(f.readline(),end="")
print(f.readline(),end="")
f.close()
发布于 2021-12-07 19:42:38
选项1是接近的,但是您的for f in line
是向后的;您需要for line in f
(即在f
文件中的每个line
上迭代)。如果在开始编写修改后的版本之前读取整个文件,也会更容易。
# Read a copy of the file into memory as a list.
with open("Odin.txt") as f:
lines = list(map(str.strip, f.readlines()))
# Write out the new content.
with open("Odin.txt", "w") as f:
for line in lines:
f.write(f"{line}={eval(line)}\n")
>cat Odin.txt
4-1
9-3
>python odin.py
>cat Odin.txt
4-1=3
9-3=6
发布于 2021-12-07 19:47:25
我可能会这样做:
import re
output = ""
with open("New Text Document.txt", "r") as file:
# This gets the expression before the "=" and removes all the leading and trailing whitespaces
text = [(re.sub("=(.*)", "", line)).strip() for line in file.readlines()]
for line in text:
try:
output += f"{line} = {eval(line)}\n"
except SyntaxError:
pass
with open("New Text Document.txt", "w") as file:
file.write(output)
基本上,先读文档,然后把我想要写的所有东西都放在一个变量中。然后,我只需在写入模式下再次打开它并编写输出。
https://stackoverflow.com/questions/70265802
复制相似问题