【问题标题】:How do I let the program "read" and copy the content of a text file?如何让程序“读取”并复制文本文件的内容?
【发布时间】:2021-02-20 00:13:33
【问题描述】:

所以,如果我有一个程序可以保存,例如外部 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

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

【问题讨论】:

标签: python store


【解决方案1】:

我认为你想要读取整个文件,检查其中是否有 '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')

【讨论】:

    【解决方案2】:
    x = open("example.txt", "w")
    x.write(str(100))
    x.close
    exit
    

    之后

    x=open("example.txt","r")
    num=x.read()
    print(num)
    x.close
    

    【讨论】:

      【解决方案3】:

      你的意思是读取文件吗?

      试试这样的:

      number = 100
      
      # Save number
      with open("example.txt", "w") as file:
          file.write(str(number))
      
      # Retrive number
      with open("example.txt", "r") as file:
          number = file.read()
      

      【讨论】:

        猜你喜欢
        • 2013-05-13
        • 1970-01-01
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        • 2012-12-26
        • 1970-01-01
        • 2016-07-06
        • 1970-01-01
        相关资源
        最近更新 更多