将流对象指向另一个流

问题描述 投票:0回答:1

我在外部位置有一个文件流对象,并希望将该流作为类似文件的对象传递给pygresql。那行得通,但是我想用替换对流进行一些更改。

import gzip
import pgdb

stream = gzip.open(external_location, 'r')
myConnection = pgdb.connect( host='x.x.x.X', user='test', password='test', database='test' )
cursor = myConnection.cursor()
cursor.copy_from(stream, 'test_table')

我不想在本地保存文件的临时副本。我想将流直接指向PostgreSQL,但是在旅途中的每次迭代中都要进行一些更改。

stream = gzip.open(external_location, 'r')
manipulated_stream = (line.replace('a', 'b') for line in stream.readlines())
cursor.copy_from(manipulated_stream, 'test_table')

但是作为一个类似文件的对象,我可以将其传递给copy_from命令。

python python-3.x postgresql io stream
1个回答
0
投票

最后,我找到了this解决方案,该解决方案基本上是根据生成器表达式创建一个stringIOBase类。

© www.soinside.com 2019 - 2024. All rights reserved.