Can't read from tempfile in Python - 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...

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()

file.seek returns None.
You should separated following statement:
print temp.seek(0).read()
into two statements:
temp.seek(0)
print temp.read()

Related

Python os.mknod in windows

I was trying to use the os.mknod function in Python 3.5.0 in Windows 7, however I find the error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
os.mknod
AttributeError: module 'os' has no attribute 'mknod'
I guess it's supposed to be there, since https://docs.python.org/3/library/os.html doesn't say anything about limited availability. Is there another option to use for a similar function in Windows? I'm just looking to create an empty file in a specific path, and I was thinking calling open(path, 'w') is kinda ugly for this.
I don't know if this might be a version specific problem since I've never used Python in Windows before.
Since commit in 2016, this is now documented:
Availability: Unix.
I'm new here and on Python World (although learning kind of quickly...), and just stumbled uppon the same issue.
My suggestion: for now, I would just go with the following and turn a blind eye on it...
with open('name_your_file.extention', 'w') as an_alias_for_it:
pass
In the end, it's not neat, but will be naturally "portable" among POSIX and NT systems.

python 2.7.9/pycharm 4/windows7: 'file' object has no attribute 'readall'

I'm trying to write some VERY trivial thing in pycharm.
Problem:
sourceText = ""
with open("lang.txt", "rt") as sourceFile:
sourceText = sourceFile.readall()
print sourceText
when I enter "." after "sourceFile", I get popup that offers me "readall()" method. However, when I attempt to run the script, I get"
Traceback (most recent call last):
....languages/languages.py", line 4, in <module>
sourceText = sourceFile.readall()
AttributeError: 'file' object has no attribute 'readall'
The method is documented (I get popup, can get documentation for this method using Ctrl+Q) but it seems to be inaccessible.
I'm a bit confused.
I'd like to either:
Not receive any popups for inaccessible methods in pycharm.
Or figure out why I can't see it despite it being documented.
Advice?
I'm using windows 7 64 bit, and have two python 2.7.9 installations (32bit and 64bit), with 64bit being in path 1st. Pycharm is 4.0.5 community edition.
You are correct that readall is documented for the io module, but it's complaining about file, which does not have that method. You want the read() method to read all the data in the file in one large clump. You could also use readlines() which well return a list. I have the Pro 3.4 edition of PyCharm and it does not do this. I would report this as a bug to PyCharm.

Learn python the hard way, exercise 25

Hello everyone i am new to the python language and i have chosen learn python the hard way to learn it and to better my understanding... I am stumped on exercise 25 , When we import the code directly into the terminal
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
And then I get an attribute error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'break_words'
I am using python 2.7 on
windows 7 please help..... http://learnpythonthehardway.org/book/ex25.html
It appears to me that the exercise does not instruct the learner to save the file prior to the import. In order for this to work, you've got to save the code that defines the break_words function in a file called ex25.py using your text editor. Then, from the same directory open the python interpreter by typing:
python
and you should be able to import ex25 and run the break_words function which the ex25.py module has defined.
The code in your link for ex25.py does include that function - that yours doesn't suggests that you've somehow missed it when you transcribed the code into your file. Check that your ex25.py includes all the code from the page, and in particular contains this function (it's the very top one):
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
Consider pasting the code into your editor in preference to transcribing it in order to avoid errors like this.

Python 3 operator >> to print to file

I have the following Python code to write dependency files of a project. It works fine with Python 2.x, but while testing it with Python 3 it reports an error.
depend = None
if not nmake:
depend = open(".depend", "a")
dependmak = open(".depend.mak", "a")
depend = open(".depend", "a")
print >>depend, s,
Here is the error:
Traceback (most recent call last):
File "../../../../config/makedepend.py", line 121, in <module>
print >>depend, s,
TypeError: unsupported operand type(s) for >>:
'builtin_function_or_method' and '_io.TextIOWrapper'
What is the best way to get this working with Python 2.x and 3.x?
In Python 3 the print statement has become a function. The new syntax looks like this:
print(s, end="", file=depend)
This breaking change in Python 3 means that it is not possible to use the same code in Python 2 and 3 when writing to a file using the print statement/function. One possible option would be to use depend.write(s) instead of print.
Update: J.F. Sebastian correctly points out that you can use from __future__ import print_function in your Python 2 code to enable the Python 3 syntax. That would be an excellent way to use the same code across different Python versions.
print() is a function in Python 3.
Change your code to print(s, end="", file=depend), or let the 2to3 tool do it for you.
Note that starting in Python 3.6.3 (September 2017), the error message for this case will be changing to recommend the Python 3 spelling:
>>> print >> sys.stderr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>:
'builtin_function_or_method' and '_io.TextIOWrapper'.
Did you mean "print(<message>, file=<output_stream>)"?
(Explicit line breaks added to avoid side-scrolling - the actual error message just wraps at the width of your terminal window)
I can propose at least two ways.
1 - if-else way with eval() trick (works with stdout as well as with a file).
import sys
def println(s, f=sys.stdout):
if sys.version_info[0] < 3:
print >>f, s
else:
func = eval('print')
func(s, end='\n', file=f)
f = open('file.txt', 'a')
println('msg') # print to stdout
println('msg', f) # print to file
f.close()
2 - Use write() instead of print().
f = open('file.txt', 'a')
f.write("%s\n" % 'msg')
f.close()
Tested both scripts on Python 2.7.17 and 3.6.9.

Another Python module reload question

Here is my code to reload a python module using the reload() build in function. I have looked at some (not all :) ) the other questions and answers in stackoverflow but to get my code to work I still need to do a os.remove('m.pyc'). Can anybody maybe explain it to me or show me how I need to change my code to make the below work without the remove.
import os
open('m.py','wt').write(r'def f(str): print "Sooo Original : %s"%(str)')
import m
m.f('Original')
os.remove('m.pyc')
open('m.py','wt').write(r'def f(str): print "Not so original : %s"%(str)')
m = reload(m)
m.f('Copy')
By replacing your remove statement with time.sleep(1) to prevent both files from being created nearly simultaneously, I obtain the correct result. I guess the problem is that both files have the same time stamp which prevents Python from detecting the change and truly reload the module.
I get a different problem on my machine.
Traceback (most recent call last):
File "test.py", line 8, in <module>
m.f('Original')
AttributeError: 'module' object has no attribute 'f'
I've noticed that you didn't close your file, so it may that the contents of the file are being held in a buffer and are waiting to be written to disk. So when you come to reloading the module, python still sees the original version of the file.
From the documentation for file.write
write(...)
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
Does the following work for you?
f = open('m.py','wt')
f.write(r'def f(str): print "Sooo Original : %s"%(str)')
f.close()
import m
m.f('Original')
f = open('m.py','wt')
f.write(r'def f(str): print "Not so original : %s"%(str)')
f.close()
m = reload(m)
m.f('Copy')

Categories

Resources