我有一个脚本,它将用户输入值从问题写入txt文件。另一个脚本需要能够打开该文件并读取这些答案。我一直试图在txt文件中以x=y格式编写值,但是当在另一个脚本中调用时,它会抛出一个错误,说明变量没有定义。这让我相信,我只是没有正确格式化临时txt文件,以便python读取这些信息。如何将多个变量和值存储在txt文件中,以便python能够将它们作为变量名读取?
这里是第一个脚本如何存储我的值。(单行)
timeIn=18 2019年1月11:39 supportID=Andy branch=Bristow clientID=Cindy Lou reason=grinch偷走圣诞节
这里是我试图按变量名读取值时遇到的错误。
Traceback (most recent call last):
File "script2.py", line 9, in <module>
f.write('[Time In] '+ timeIn)
NameError: name 'timeIn' is not defined
我的问题是如何格式化txt文件中的这些文件以供另一个脚本读取?
编辑1:我以的方式在第二个脚本中打开txt文件
t=open("testtmp.txt","r")
编辑2:我不会像在单独的行上(x)一样编写值。我现在正在尝试读取这些值,以便写入另一个文件。。
发布于 2019-01-18 22:07:34
我就是这样解决我的问题的(.txt格式):
首先,我在原始值中写入了一个分隔它们的行。
t=open("nbsstmp.txt", "w")
t.write(timeIn+' \n')
t.write(supportID+' \n')
t.write(branch+' \n')
t.write(clientID+' \n')
t.write(problem+' \n')
t.close()
然后,我用以下的方式把它们读回来了。
t=open("nbsstmp.txt","r")
f=open("Support_Access_Log.txt","a")
timeIn=(t.readlines((1)))
a=(str(timeIn))
supportID=(t.readlines(2))
b=(str(supportID))
branch=(t.readlines(3))
c=(str(branch))
clientID=(t.readlines(4))
d=(str(clientID))
problem=(t.readlines(5))
e=(str(problem))
f.write('[Time In] ')
f.write(a.replace("['","").replace("']","").replace("\\n",""))
f.write(' [Support ID] ')
f.write(b.replace("['","").replace("']","").replace("\\n",""))
f.write(' [Branch] ')
f.write(c.replace("['","").replace("']","").replace("\\n",""))
f.write(' [Support Client] ')
f.write(d.replace("['","").replace("']","").replace("\\n",""))
f.write(' [Reason] ')
f.write(e.replace("['","").replace("']","").replace("\\n",""))
f.close()
t.close()
发布于 2019-01-18 17:54:32
这种键值数据在json文件中更容易处理。
您可以使用库json来处理它。
https://docs.python.org/2/library/json.html
使用文本文件时,您只是在处理字符串,因此您需要在读取数据后将其解析为可用的格式。
https://stackoverflow.com/questions/54259032
复制相似问题