gpt4 book ai didi

python - 无法写入文本文件

转载 作者:行者123 更新时间:2023-11-28 22:06:52 24 4
gpt4 key购买 nike

我正在运行一些测试并且需要写入一个文件。当我运行测试时,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创建文件的权限问题吗?我已确保关闭对该文件的所有其他读取,因此不应锁定该文件。

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

谢谢

最佳答案

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

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

关于python - 无法写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2949581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com