【问题标题】:School assignment file manipulations with - operator [closed]使用 - 操作员进行学校作业文件操作[关闭]
【发布时间】:2022-01-12 20:39:58
【问题描述】:

我的文本文档有两组数字 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()

【问题讨论】:

  • 您应该首先确定您使用的语言,然后解释您在尝试编码时遇到的具体问题。
  • 一些前后会很方便。

标签: python text document


【解决方案1】:

我可能会这样做:

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)

所以基本上先阅读文档,然后将我想在文件中写入的所有内容放在一个变量中。然后我只需以写入模式再次打开它并写入我的输出。

【讨论】:

  • 感谢您的帮助 :)
  • 完全没问题:)
【解决方案2】:

您的选项 1 很接近,但您的 for f in line 倒退了;你想要for line in f(即遍历file 中的每个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

【讨论】:

  • 我是如此接近,但到目前为止感谢您的帮助:)
猜你喜欢
  • 2014-10-25
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多