0

次を使用して、あるファイルから読み取り、別のファイルに書き込もうとしています。

with open('example2') as inpf, open('outputrt','w') as outf:  
    for l in inpf:
        outf.write(l)  

しかし、1 行目で構文エラーが発生します。

"with open('example2') as inpf, open('outputrt','w') as outf:" pointing at "inpf,"

私のpythonバージョンは2.6です。構文に誤りがありますか?

4

2 に答える 2

2

この構文は 2.7+ でのみサポートされています。
2.6では次のことができます:

import contextlib

with contextlib.nested(open('example2'), open('outputrt','w')) as (inpf, outf):  
    for l in inpf:
        outf.write(l) 

または、これを行う方がきれいに見えるかもしれません(これは私の好みです):

with open('example2') as inpf:
    with open('outputrt','w') as outf:  
        for l in inpf:
            outf.write(l)  
于 2012-05-25T00:04:45.097 に答える
0

Python バージョン <= 2.6 では、次を使用できます。

inPipe = open("example2", "r")
outPipe = open("outputrt", "w")
for k in inPipe:
    outPipe.write(k)
于 2012-05-25T01:18:57.583 に答える