所以......我正在学习python。我试图创建一个保存变量值的文件(文件是arqLog,变量是novoArq),但问题是:变量的值更新为+1,但它没有'发生在文件内部。我希望变量在文件内部更新,以便我可以将其作为字符串添加到.dat文件名并创建某种备份,以便程序继续从停止的位置创建.datx文件。 (Python 3.4)
x = []
y = []
novoArq = 1
cwd = os.getcwd()
def main():
global novoArq
global cwd
resposta = eval(input('\nChose one of the options below:\n\n1. Create data\n2. Plot data\n3. Quit\n\n--> '))
if resposta == 1:
try:
os.mkdir('coordenadas')
arqLog = open(cwd+'/coordenadas/dat.log','w')
print('\nA new folder has been created: '+cwd+'/coordenadas')
arqLog.write(str(novoArq))
arqLog = open(cwd+'/coordenadas/dat.log','r')
arqLog2 = arqLog.read()
x = input('\nType the values for X separated by coma (ex: -10,2.3,5): ')
y = input('\nType the values for Y separated by coma (ex: -10,2.3,5): ')
arqx = open(cwd+'/coordenadas/x.dat'+arqLog2,'w')
arqx.write(x)
arqx.close()
arqy = open(cwd+'/coordenadas/y.dat'+arqLog2,'w')
arqy.write(y)
arqy.close()
print("\nThese values were saved: "+cwd+"/coordenadas/x.dat"+arqLog2+" e y.dat"+arqLog2)
arqLog.close()
novoArq+=1
main()
except:
arqLog = open(cwd+'/coordenadas/dat.log','r')
arqLog2 = arqLog.read()
x = input('\nType the values for X separated by coma (ex: -10,2.3,5): ')
y = input('\nType the values for Y separated by coma (ex: -10,2.3,5): ')
arqx = open(cwd+'/coordenadas/x.dat'+arqLog2,'w')
arqx.write(x)
arqx.close()
arqy = open(cwd+'/coordenadas/y.dat'+arqLog2,'w')
arqy.write(y)
arqy.close()
print("\nEsses dados foram arquivados em "+cwd+"/coordenadas/x.dat"+arqLog2+" e y.dat"+arqLog2)
arqLog.close()
novoArq+=1
main()
当我打印novoArq时,它会输出更新的值,但是当我打印arqLog2时,它每次输出1。
答案 0 :(得分:0)
我认为这是问题的根源:
arqLog = open(cwd+'/coordenadas/dat.log','w')
print('\nA new folder has been created: '+cwd+'/coordenadas')
arqLog.write(str(novoArq))
arqLog = open(cwd+'/coordenadas/dat.log','r')
您正在打开文件dat.log进行写入,然后在关闭它之前将其打开以进行读取,
您应先关闭该文件,然后再将其打开以进行阅读:
arqLog = open(cwd+'/coordenadas/dat.log','w')
print('\nA new folder has been created: '+cwd+'/coordenadas')
arqLog.write(str(novoArq))
argLog.close() # **CLOSE THE FILE AFTER WRITE THEN OPEN IT**
arqLog = open(cwd+'/coordenadas/dat.log','r')
答案 1 :(得分:0)
如果novoArq
没有失败,您只能写os.mkdir('coordenadas')
。
它在第一次失败后因此永远不会写出1
以外的任何内容。