Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file in universal-newline mode when using pkg_resources?

I am processing a CSV file and have the following working code:

reader = csv.reader(open(filename, 'rU'), dialect='excel')
header = reader.next()

However, to be compatible with elsewhere in the codebase, I need to use a file object using pkg_resources.resource_stream, as follows:

fileobj = pkg_resources.resource_stream('foo', 'tests/bar.csv')
reader = csv.reader(fileobj, dialect='excel')
header = reader.next()

(I'm simplifying here - basically the csv.reader code is in a function over which I don't have control, and it expects a fileobj.)

This throws the following error.

Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

Any idea how I can use universal-newline mode with my fileobj? I can't see anything about this in the pkg_resources documentation.

Thanks.

like image 411
AP257 Avatar asked Dec 05 '25 11:12

AP257


1 Answers

If the stream always has an fd (e.g. because it's a normal opened file on the filesystem), you can use os.fdopen(fileobj.fileno(), 'rU') to open it with the right mode.

like image 154
adw Avatar answered Dec 08 '25 02:12

adw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!