python"with"命令和csv阅读器

use*_*015 0 python csv

我有csv读者和作家.我知道你必须打开和关闭底层对象.一种方法是首先创建文件对象f,使用csv reader然后使用f.close().

但是,我似乎无法做到以下几点:

with open(outputpath) as f_outputfile:

    outputfile = csv.writer(f_outputfile)

OTHER CODE HERE
Run Code Online (Sandbox Code Playgroud)

我想要做的是立即打开一堆读者和一堆作者,让它们全部自动关闭.但是,这是否意味着我有一个嵌套的"With"块?

Eri*_*ric 5

写作:

with open(outputpath) as f_outputfile:
    outputfile = csv.writer(f_outputfile)

OTHER CODE HERE
Run Code Online (Sandbox Code Playgroud)

基本上与以下相同:

f_outputfile = open(outputpath)
try:
    outputfile = csv.writer(f_outputfile)
finally:
    f_outputfile.close() 

OTHER CODE HERE
Run Code Online (Sandbox Code Playgroud)

如果OTHER CODE HERE依赖于打开的文件,它将不起作用.