使用 - 运算符操作学校作业文件

School assignment file manipulations with - operator

我有包含两组数字 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()

你的选项 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

我可能会这样做:

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)

所以基本上是先看文档,把我想写的文件都放在一个变量里。然后我简单地再次以写入模式打开它并写入我的输出。