我在名爲1.htm - 100.htm的文件夾中有100個文件。 我運行此代碼從文件中提取一些信息,並將提取的信息放入另一個文件final.txt中。目前,我必須爲100個文件手動運行程序。我需要構建一個可以運行程序100次的循環,讀取每個文件一次。循環遍歷文件
下面是對文件6.htm代碼(在我需要在我的代碼做詳細的編輯詳細講解和藹):
import glob
import BeautifulSoup
from BeautifulSoup import BeautifulSoup
fo = open("6.htm", "r")
bo = open("output.txt" ,"w")
f = open("final.txt","a+")
htmltext = fo.read()
soup = BeautifulSoup(htmltext)
#print len(urls)
table = soup.findAll('table')
rows = table[0].findAll('tr');
for tr in rows:
cols = tr.findAll('td')
for td in cols:
text = str(td.find(text=True)) + ';;;'
if(text!=" ;;;"):
bo.write(text);
bo.write('\n');
fo.close()
bo.close()
b= open("output.txt", "r")
for j in range (1,5):
str=b.readline();
for j in range(1, 15):
str=b.readline();
c=str.split(";;;")
#print c[1]
if(c[0]=="APD ID:"):
f.write(c[1])
f.write("#")
if(c[0]=="Name/Class:"):
f.write(c[1])
f.write("#")
if(c[0]=="Source:"):
f.write(c[1])
f.write("#")
if(c[0]=="Sequence:"):
f.write(c[1])
f.write("#")
if(c[0]=="Length:"):
f.write(c[1])
f.write("#")
if(c[0]=="Net charge:"):
f.write(c[1])
f.write("#")
if(c[0]=="Hydrophobic residue%:"):
f.write(c[1])
f.write("#")
if(c[0]=="Boman Index:"):
f.write(c[1])
f.write("#")
f.write('\n');
b.close();
f.close();
f.close();
print "End"
這就是http://docs.python.org/3/library/fileinput.html的用途。 – 2014-03-24 14:00:49
另外,'對於範圍(1,5)中的j:'從未使用過?或者至少你不要在任何地方使用'j',並且製表符縮進在多個位置是完全錯誤的。 – Torxed