大家好,我有一个文本文档,其中有两组数字 4-1 和 9-3 代码需要读取它们并写入同一个文本文档中,并且需要注意换行符,然后代码需要计算它们并打印而不需要输入 tnx 寻求帮助
我已经尝试过了
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()
你的选项1很接近,但你的
for f in line
是向后的;你想要 for line in f
(即迭代 line
ile 中的每个 f
)。如果您在开始写出修改后的版本之前阅读整个文件,也会更容易。
# 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
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)
所以基本上先阅读文档,然后将我想要在文件中写入的所有内容放入变量中。然后我只需在写入模式下再次打开它并写入我的输出即可。