首页 > 解决方案 > 如何让程序“读取”并复制文本文件的内容?

问题描述

因此,如果我有一个程序可以在外部 txt 中保存例如数字。文件

x = open("example.txt", "w")
x.write(str(100))
x.close
exit

如果我再次启动该程序,如何访问该号码?

pseudocode

open example.txt
read 100
copy 100
"paste" it in my program (e.g. save it as a var) to use it in my program

我希望你能得到我想要表达的东西。我确信有更简单的方法来存储来自另一个“会话”的信息,如果你不介意的话,我也想知道它们,但我也希望能回答这个问题。

标签: pythonstore

解决方案


我认为您想要读取整个文件,检查其中是否包含“100”,然后读取或写入它:

with open('example.txt') a f:
  s=f.read()
if '100' in s:
  print(100)
else:
  with open('example.txt','w') as g:
    g.write('100')

推荐阅读