为什么我的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 
+0

您可能无法读取同一个文件! – Rishav

+0

@RishavKundu:如果你使用'.seek()'方法重放文件,你可以。 :)对于像这样的小文件,最好将它读入列表中,如下所述。但是为了处理一个非常大的文件,可能需要使用'.seek()'。 –

+0

@ PM2Ring谢谢!不知道哈哈。 – Rishav

可变性反对你; s引用的文件已经被外部for循环的第二次迭代读取。

考虑将第二行更改为s = open('domainlist', 'r').read().split('\n'),将第四行更改为for domain in s:。这将存储domainlist文件的读数,并避免您尝试多次读取该文件。

+0

没错。温度在临时温度。 Voltron在哪里? – dsgdfg

+0

@SDilmac *叹*好,如果你想要一个也鼓励好风格的答案,我想,是的,我可以强烈建议使用类似左值对象的更普遍使用。 : - /编辑说这样。 – user

的问题是在这里:

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

这是很简单的:

for host in open('hosts'): 
    for domain in open('domainlist'): 
     print host.strip()+'.'+domain.strip() 
+0

请注意,open()默认为读取,当没有更多引用时,文件会关闭。 – Skaperen

+1

这就像它变得简单一样。我只会添加你应该明确地关闭这些文件,或者在'with'语句中打开它们。 – mhawke

+0

另外,'seek(0)'比重新打开文件要快,但是,这对OP的数据来说完全可以忽略不计。 – mhawke