为什么我的Python里面没有工作?
问题描述:
我是新来的python和我见过的例子不回答我的问题。为什么我的Python里面没有工作?
我试图读取两个文件,主机和domainlist,并将domainlist的内容附加到主机上,添加句点并打印结果。
我已经为第一台主机正确执行了这一操作,但只打印了随后的两个主机。
h = open('hosts', 'r')
s = open('domainlist', 'r')
for host in h.read().split():
for domain in s.read().split('\n'):
print host+"."+domain
h.close()
s.close()
这打印出以下
google.gov
google.com
google.net
google.org
google.co.uk
google.com.au
google.com.sg
yahoo.
dogpile.
的 '主人' 文件包含下列主机
google
yahoo
dogpile
的 '的domainlist' 包含以下
gov
com
net
org
co.uk
com.au
com.sg
答
的问题是在这里:
for domain in s.read().split('\n'):
在你的外for循环的第一次迭代,你读的文件。在第二次迭代中,他的文件指针已经在文件的末尾,因此你没有更多的东西要循环。我建议你在开始时阅读一次文件,然后遍历列表:
h = open('hosts', 'r')
s = open('domainlist', 'r')
domains = s.read().split('\n')
for host in h.read().split():
for domain in domains:
print host+"."+domain
h.close()
s.close()
答
什么是所有这些分裂和阅读?
对文件的简单迭代不需要使用split()
和read()
- 您可以直接在文件对象上进行迭代。我还建议的with
使用:
with open('hosts') as h, open('domainlist') as s:
for host in h:
for domain in s:
print '{}.{}'.format(host.strip(), domain.strip())
s.seek(0)
注意使用seek(0)
返回到每个主机的域名文件的开头。
输出
google.gov google.com google.net google.org google.co.uk google.com.au google.com.sg yahoo.gov yahoo.com yahoo.net yahoo.org yahoo.co.uk yahoo.com.au yahoo.com.sg dogpile.gov dogpile.com dogpile.net dogpile.org dogpile.co.uk dogpile.com.au dogpile.com.sg
另一种方法是使用itertools.product()
:
from itertools import product
with open('hosts') as h, open('domainlist') as s:
print '\n'.join('.'.join(x.strip() for x in t) for t in product(h, s))
+1
更好编码。新手也应该这样学习。并学习寻找Python中已有的东西以及像strip()这样的默认值。 – Skaperen
您可能无法读取同一个文件! – Rishav
@RishavKundu:如果你使用'.seek()'方法重放文件,你可以。 :)对于像这样的小文件,最好将它读入列表中,如下所述。但是为了处理一个非常大的文件,可能需要使用'.seek()'。 –
@ PM2Ring谢谢!不知道哈哈。 – Rishav