2016-09-29 121 views
0

我陷入了一些我認爲應該足夠簡單的事情。 我正在創建一個包含json字符串的文件,以導入到postgres數據庫中。但是,即使python腳本的內部測試顯示它存在,該文件也不會導入。直到腳本完成後文件才寫完

但是,如果我在腳本完成後執行postgres導入,它將複製正常,或者如果我將它們包裝在單獨的腳本中並從單個腳本中調用它,它將起作用,但如果兩個請求都處於相同腳本。我試過close(),fsync和flush但沒有運氣..

任何人都可以幫忙嗎?

相關代碼如下。

command=str("PGPASSWORD=password psql -d database -U postgres -V -c \"copy import.table from Data.txt'\"") 
print command 

    dataFile=open('Data.txt','w') 
    for x in xx: 
     xString=json.loads(data) 
     xString[i]['source']=x 
     xString[i]['created_at'].replace('"','') 
     xStringJson=json.dumps(xString) 
     dataFile.write(xStringJson) 
     dataFile.close 
     dataFile.flush() 
     os.fsync(dataFile) 
     print os.path.isfile('Data.txt') 
     pg_command(command) 
    i=i+1 
+1

'f.close'不是'f.close()' –

回答

4

您未關閉文件。

這什麼都不做,原因是其缺少括號:

dataFile.close 

但事件如果它沒有關閉,它將通過XX做它在第一次迭代。

這樣來做:

with open('Data.txt','w') as dataFile: 
    for x in xx: 
     # write to the file 

# when you are back here, the file is flushed, closed, and ready to be read. 
+0

謝謝,我沒有注意到這一點,它拋出也不例外。謝謝你的建議。 – Mokadillion

相關問題