【问题标题】:Get values form a txt, increase them save them in the same txt从 txt 中获取值,增加它们将它们保存在同一个 txt 中
【发布时间】:2018-03-24 19:57:23
【问题描述】:

我正在尝试从 txt 中获取一些值,增加它们(直到这里一切正常),然后在文件中写入新变量,但我无法在文件中写入变量,尽管我已经更改了变量在一个字符串.. 代码是

with open("setup.txt", "r") as f:
  for i, line in enumerate(f):
     str = line.split(",")
     if i == 0:
        minL = int(str[0])
        maxL = int(str[1])

        minL += 2
        maxL += 2
      elif i == 1:
        minF = int(str[0])
        maxF = int(str[1])
        minF += 1
        maxF += 1
minL = str(minL)
with open("setup.txt", "w") as f:
    f.write(minL)
    f.close()

txt 只是:

15, 25
2, 9

编辑********* 对不起,我复制代码时出错了,我已经将“w”作为写作模式,但这不起作用

错误是

line 15, in <module>
minL = str(minL)
NameError: name 'minL' is not defined

但我定义了 minL

【问题讨论】:

  • 大概是在抱怨你试图写入一个你刚刚在read 模式下明确打开的文件?
  • 错误是什么
  • 另外,使用with open时,不需要close
  • 错误信息说没有定义minL,所以for循环似乎永远不会运行。也许文件 setup.txt 是空的?

标签: python string variables int


【解决方案1】:

17 是您的预期输出吗?

我复制并修改了您的代码:

with open("setup.txt", "r") as f:
    for i, line in enumerate(f):
        stri = line.split(",")
        if i == 0:
            minL = int(stri[0])
            maxL = int(stri[1])

            minL += 2
            maxL += 2
        elif i == 1:
            minF = int(stri[0])
            maxF = int(stri[1])
            minF += 1
            maxF += 1
minL = str(minL)
with open("setup.txt", "w") as f:
    f.write(minL)
    f.close()

我收到了缩进错误(我已修复)并将str = line.split(",") 更改为stri = line.split(",")

【讨论】:

  • 谢谢,是的,输出应该是 17!真的很感激!
猜你喜欢
  • 1970-01-01
  • 2022-10-18
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多