直到脚本完成后文件才写完

问题描述:

我陷入了一些我认为应该足够简单的事情。 我正在创建一个包含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()' –

您未关闭文件。

这什么都不做,原因是其缺少括号:

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