无法写入文本fi

2024-04-29 04:10:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一些测试,需要写入一个文件。当我运行测试时,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不允许创建文件的情况下,这会是一个权限问题吗?我已经确定了对这个文件的所有其他读操作都已关闭,所以我不应该锁定该文件。在

有人能提供任何建议吗?在

谢谢


Tags: 文件self脚本falseassertresultopenclass
1条回答
网友
1楼 · 发布于 2024-04-29 04:10:40

写入后,光标位于文件末尾。如果你想读课文,你必须移到开头:

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

或者,如果您在阅读之前关闭文件,它也会起作用(但对于您的情况,这可能不是更有效的方法)。在

^{pr2}$

相关问题 更多 >