无法写入文本文件

时间:2010-06-01 12:06:50

标签: python file-io

我正在运行一些测试,需要写入文件。当我运行测试时,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

当此测试运行时,没有任何值输入到文本文件中,并且在变量结果中返回一个值。

我还试过mylogfile.write(result)。如果该文件不存在则声明该文件不存在且不创建文件。

这可能是一个权限问题,其中不允许python创建文件?我确保此文件的所有其他读取都已关闭,因此我不应该锁定该文件。

任何人都可以提出为什么会发生这种情况的建议吗?

由于

1 个答案:

答案 0 :(得分: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
相关问题