Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't read from tempfile in Python

I am trying to use some temporary files in an little python script and running into problems while using the tempfile-module:

test-code

import tempfile
with tempfile.NamedTemporaryFile() as temp:
    print temp.name
    temp.write('Some data')
    print temp.seek(0).read()

output

s$ python tmpFileTester.py

/var/folders/cp/8kmr4fhs4l94y8fdc6g_84lw0000gn/T/tmpcDgrzF

Traceback

(most recent call last): File "tmpFileTester.py", line 5, in print temp.seek(0).read() AttributeError: 'NoneType' object has no attribute 'read'

--> This happens on my MacBook with MacOS 10.9 and Python 2.7.5, it also happens with "delete=False".

Any ideas? It's probably a noob-error, but I can't find the problem...

like image 496
basti Avatar asked Feb 02 '26 18:02

basti


2 Answers

Whenever you are chaining methods in Python and you get this, you can bet that one of them returns None (even if implicitly by not returning at all). The solution is generally to split up the chain over multiple lines.

temp.seek(0)
print temp.read()
like image 200
Two-Bit Alchemist Avatar answered Feb 05 '26 06:02

Two-Bit Alchemist


file.seek returns None.

You should separated following statement:

print temp.seek(0).read()

into two statements:

temp.seek(0)
print temp.read()
like image 38
falsetru Avatar answered Feb 05 '26 06:02

falsetru



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!