Reputation: 41655
I am running some tests and need to write to a file. When I run the test's the open = (file, 'r+')
does not write to the file. The test script is below:
class GetDetailsIP(TestGet):
def runTest(self):
self.category = ['PTZ']
try:
# This run's and return's a value
result = self.client.service.Get(self.category)
mylogfile = open("test.txt", "r+")
print >>mylogfile, result
result = ("".join(mylogfile.readlines()[2]))
result = str(result.split(':')[1].lstrip("//").split("/")[0])
mylogfile.close()
except suds.WebFault, e:
assert False
except Exception, e:
pass
finally:
if 'result' in locals():
self.assertEquals(result, self.camera_ip)
else:
assert False
When this test run's, no value has been entered into the text file and a value is returned in the variable result.
I havw also tried mylogfile.write(result)
. If the file does not exist is claim's the file does not exist and doesn't create one.
Could this be a permission problem where python is not allowed to create a file? I have made sure that all other read's to this file are closed so I the file should not be locked.
Can anyone offer any suggestion why this is happening?
Thanks
Upvotes: 2
Views: 3419
Reputation: 85603
After writing, your cursor is at the end of the file. If you want to read the text you have to move to the beginning:
>>> mylogfile = open("test10.txt", "w+")
>>> print >> mylogfile, 'hola'
>>> mylogfile.flush() #just in case
>>> print mylogfile.read()
#nothing because I'am at the end of the file
>>> mylogfile.seek(0)
>>> print mylogfile.read()
hola
Alternatively, it also works if you close your file before reading (but maybe this is not the more efficient method for your case).
>>> mylogfile = open("test.txt", "w")
>>> print >> mylogfile, 'hola'
>>> mylogfile.close()
>>> mylogfile = open("test.txt", "r")
>>> print mylogfile.read()
hola
Upvotes: 5