2015-05-11 55 views
1

所以...我目前正在學習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

什麼是'try:'/'除了:'for?你有什麼異常?你確定這是你實際得到的例外嗎? – abarnert

+0

此外,您似乎已複製並粘貼了一長串代碼兩次。你確定這兩個版本是相同的,還是有可能其中一個是正確的,另一個是錯誤的? – abarnert

+0

因爲os.mkdir(),我使用try和except。如果該文件夾已經存在,它會轉到except塊。我不確定這是否是更好的方式,但似乎正在工作。 –

回答

0

你只寫novoArq如果os.mkdir('coordenadas')不會失敗。

它在第一次後失敗,因此永遠不會寫入超過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') 
+0

感謝您的回答。這是有道理的,但似乎並不是問題所在。 –

+0

你是否嘗試過並沒有解決你的問題? –