无法写入文本文件

chr*_*ley 2 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
Run Code Online (Sandbox Code Playgroud)

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

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

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

任何人都可以提出任何建议,为什么会这样?

谢谢

joa*_*uin 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
Run Code Online (Sandbox Code Playgroud)

或者,它也适用于您在阅读之前关闭文件(但这可能不是更有效的方法).

>>> mylogfile = open("test.txt", "w")
>>> print >> mylogfile, 'hola' 
>>> mylogfile.close()
>>> mylogfile = open("test.txt", "r")
>>> print mylogfile.read()
hola
Run Code Online (Sandbox Code Playgroud)