英文:
How to read a ZIpFile using a specific char as newline separator, instead of \n?
问题
你好,以下是代码的翻译部分:
from zipfile import ZipFile
...
with ZipFile(flu) as zf:
for file in zf.namelist():
if not file.endswith('.sql'):
continue
with zf.open(file,"r") as f:
...
for row_b in f:
...
希望这有助于你理解代码。如果你需要更多帮助,请随时提问。
英文:
I've got this code:
from zipfile import ZipFile
...
with ZipFile(flu) as zf:
for file in zf.namelist():
if not file.endswith('.sql'):
continue
with zf.open(file,"r") as f:
...
for row_b in f:
...
I want to use the char ';' as newline separator when opening the zip file, instead of '\n'. In this way I can run the SQL statements included in the zip file also if they are formatted in more than one line.
I find out this documentation and this documentation and it seems that I can specify the newline separator when opening a stream.
I cannot understand how to do it when opening a zip file.
答案1
得分: 1
没有选项可以配置ZipExtFile
(zip.open(...)
返回的对象)的行结束字符。
但是,您可以使用以下简单的函数创建自己的缓冲读取器:
from io import BytesIO
def delimited_read(f, sep, block_size=16384):
buf = bytearray()
while True:
idx = buf.find(sep)
while idx == -1:
block = f.read(block_size)
if block == b'':
break
start = len(buf)
buf.extend(block)
idx = buf.find(sep, start)
if idx == -1:
if len(buf) > 0:
yield bytes(buf)
return
else:
yield bytes(buf[0:idx])
buf = buf[idx+1:]
然后,您可以简单地使用它:
for line in delimited_read(f, b';'):
print(line)
请注意,这是Python代码的翻译。
英文:
There is no option to configure the line ending character for ZipExtFile
(what zip.open(...)
returns).
However, you can create your own buffered reader with a simple function:
from io import BytesIO
def delimited_read(f, sep, block_size=16384):
buf = bytearray()
while True:
idx = buf.find(sep)
while idx == -1:
block = f.read(block_size)
if block == b'':
break
start = len(buf)
buf.extend(block)
idx = buf.find(sep, start)
if idx == -1:
if len(buf) > 0:
yield bytes(buf)
return
else:
yield bytes(buf[0:idx])
buf = buf[idx+1:]
And you can simply use it as:
for line in delimited_read(f, b';'):
print(line)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论