我有一个Python函数,它将列表作为参数并将其写入文件:
def write_file(a):
try:
f = open('testfile', 'w')
for i in a:
f.write(str(i))
finally:
f.close()
Run Code Online (Sandbox Code Playgroud)
我该如何测试这个功能?
def test_write_file(self):
a = [1,2,3]
#what next ?
Run Code Online (Sandbox Code Playgroud) 问题是写入文件后它是空的,我不明白为什么。这是我的代码:
self.f = tempfile.NamedTemporaryFile(delete=False)
for i in range(self.num_chars_file):
self.f.write(str(i))
reader_writer.testfile = self.f.name
print '************************'
print self.f.read()
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况,以及如何纠正这种情况?
在python中我需要从主机名获取IP:
socket.gethostbyname('www.python.org') # returns ip good
socket.gethostbyname('http://python.org') # raises error
Run Code Online (Sandbox Code Playgroud)
我需要处理以"http://"开头的主机名,所以我想出了一种方法来重新制作它们:
a = 'http://python.org'
a.replace('http://', 'www.')
print a # Why does it print http://python.org ???
Run Code Online (Sandbox Code Playgroud)
我不确定我做对了.Plz帮助我将这种类型的主机名转换为IP
我有一个正则表达式,在标签中搜索"href"属性,但它目前效果不佳:
<a[^>]* href="([^"]*)"
Run Code Online (Sandbox Code Playgroud)
它从中发现:
<a href="http://something" title="Development of the Python language and website">Core Development</a>
Run Code Online (Sandbox Code Playgroud)
这一行:
<a href="http://something"
Run Code Online (Sandbox Code Playgroud)
但我只需要找到:
http://something
Run Code Online (Sandbox Code Playgroud)