无法写入文本文件
我正在进行一些测试,需要写入一个文件。当我运行测试时,open = (file, 'r+')
并没有写入文件。下面是测试脚本:
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
当这个测试运行时,文本文件里没有输入任何值,但变量result却返回了一个值。
我也试过mylogfile.write(result)
。如果文件不存在,它会说文件不存在,并且不会创建一个新的文件。
这可能是权限问题吗?也就是说,Python没有权限去创建文件?我已经确保所有对这个文件的读取都已经关闭,所以文件应该没有被锁定。
有没有人能给我一些建议,为什么会出现这种情况?
谢谢
1 个回答
5
写完东西后,光标会停在文件的最后面。如果你想看之前写的内容,就得把光标移动到文件的开头:
>>> 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
另外,如果你在阅读之前先关闭文件也是可以的(不过这样做可能不是最有效的方法,具体要看你的情况)。
>>> mylogfile = open("test.txt", "w")
>>> print >> mylogfile, 'hola'
>>> mylogfile.close()
>>> mylogfile = open("test.txt", "r")
>>> print mylogfile.read()
hola