Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么需要嵌套读写器的with语句?_Python_Python 3.x_File Io_With Statement_Pypdf2 - Fatal编程技术网

Python 为什么需要嵌套读写器的with语句?

Python 为什么需要嵌套读写器的with语句?,python,python-3.x,file-io,with-statement,pypdf2,Python,Python 3.x,File Io,With Statement,Pypdf2,这在编写副本时起作用 现在让我们用将最后三行移出: with open(pdf,'rb') as fin: reader = PyPDF2.PdfFileReader(fin) new_pdf = PyPDF2.PdfFileWriter() for i in range(reader.numPages): new_pdf.addPage(reader.getPage(i)) out_file = pdf if not create_copy

这在编写副本时起作用

现在让我们用将最后三行移出

with open(pdf,'rb') as fin:
    reader = PyPDF2.PdfFileReader(fin)
    new_pdf = PyPDF2.PdfFileWriter()

    for i in range(reader.numPages):
        new_pdf.addPage(reader.getPage(i))

    out_file = pdf if not create_copy else self._new_copy(pdf)
    with open(out_file,'wb') as fout:
        new_pdf.write(fout)
这将创建一个具有正确页数的pdf,但是所有页面都是空白的,即使在写入新文件时也是如此。(请注意,将
new\u pdf=…
移出也不会改变任何内容)


为什么??我能做些什么呢?因为我希望最终必须用
将这三行从第一个
中移出,以便提供覆盖支持。(除非我只是创建了一个副本,然后重新命名,这是我想避免的。)

这是一种猜测,因为我不熟悉这个模块,也不想费心去做


然而,从文档来看,似乎需要一个,其中包含对该页面所属的PDF文件的引用。因此,我的猜测是,
addPage
不会立即创建原始PDF中页面的副本,而只是对该页面的引用,当该文件在新PDF编写之前关闭时,该页面的内容将丢失。

这是一种胡乱猜测,因为我对该模块不熟悉,也懒得解释


然而,从文档来看,似乎需要一个,其中包含对该页面所属的PDF文件的引用。所以我猜,
addPage
不会立即创建原始PDF中页面的副本,而只是对该页面的引用,当该文件在编写新PDF之前关闭时,该页面的内容丢失。

在第一种情况下,如果不创建副本,打开相同的文件进行读写是否真的有效?@AndreasDeak当然不会。我只能在这里猜测,但可能
addPage
并没有将页面复制到
新pdf
,而只是对原始文件的引用,然后该文件在
结束时用
@tobias\u k关闭。当
创建副本
设置为
时,我修改了在
r+b
中打开文件的方法。这样我就可以将
fin
作为参数传递给
new\u pdf.write()
。这样行得通,所以我怀疑你是对的。想从你的评论中得出答案吗?在第一种情况下,打开同一个文件进行读写是否真的有效?如果不创建副本,我只能在这里猜测,但可能
addPage
并没有真正将页面复制到
new\u pdf
中,而只是对原始文件的引用,然后该文件在
末尾关闭,使用
@tobias\k我修改了方法,在
r+b
中打开文件,当
创建副本
设置为
False
时。这样我就可以将
fin
作为参数传递给
new\u pdf.write()
。这样行得通,所以我怀疑你是对的。想从你的评论中得到答案吗?
with open(pdf,'rb') as fin:
    reader = PyPDF2.PdfFileReader(fin)
    new_pdf = PyPDF2.PdfFileWriter()

    for i in range(reader.numPages):
        new_pdf.addPage(reader.getPage(i))

out_file = pdf if not create_copy else self._new_copy(pdf)
with open(out_file,'wb') as fout:
    new_pdf.write(fout)