ValueError: I/O operation on closed file. with python3

Adam Mercer ramercer at gmail.com
Wed Jun 12 01:50:27 EDT 2013


Hi

I'm trying to update one of my scripts so that it runs under python2
and python3, but I'm running into an issue that the following example
illustrates:

$ cat test.py
try:
  # python-2.x
  from urllib2 import urlopen
  from ConfigParser import ConfigParser
except ImportError:
  # python-3.x
  from urllib.request import urlopen
  from configparser import ConfigParser

server='http://www.lsc-group.phys.uwm.edu/~ram/files'

fp = urlopen('%s/latest.ini' % server).fp
cp = ConfigParser()
cp.readfp(fp)
print(cp.get('version', '10.8'))
$

This works as expected when using python2:

$ python2.7 test.py
5.2.10
$

but when using python3 I receive the following error:

$ python3.3 test.py
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    cp.readfp(fp)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/configparser.py",
line 753, in readfp
    self.read_file(fp, source=filename)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/configparser.py",
line 708, in read_file
    self._read(f, source)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/configparser.py",
line 1010, in _read
    for lineno, line in enumerate(fp, start=1):
ValueError: I/O operation on closed file.
$

Is there a way to get this working in both python2 and python3?

This is a small script and I'm starting to have some users wanting to
use python3 and others sticking to python2 so I'd like to accommodate
them both if possible.

Cheers

Adam



More information about the Python-list mailing list