2010-06-01 134 views
2

我正在運行一些測試並需要寫入文件。當我運行測試時,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不允許創建文件?我已經確保所有其他閱讀文件都關閉,所以我不應該鎖定文件。

任何人都可以提供任何建議,爲什麼發生這種情況?

謝謝

+0

您正在關閉文件句柄而不寫入它。 – 2010-06-01 12:09:12

+0

@Srinivas Reddy Thatiparthy - 'print >> mylogfile,result'應該在寫入之前關閉。我也嘗試過'mylogfile.write(result)' – chrissygormley 2010-06-01 12:11:54

+0

我不是Python專家,但是不是用於讀取的r +和用於寫入的w +? – 2010-06-01 12:15:20

回答

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

謝謝,這項工作是完美的。 +1 – chrissygormley 2010-06-01 12:35:54

+0

@joanquin - 這更好。這使得它更加整潔。謝謝 – chrissygormley 2010-06-01 13:59:31