【问题标题】:Looping through files [closed]循环文件[关闭]
【发布时间】:2014-03-24 13:55:54
【问题描述】:

我在名为 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"

【问题讨论】:

  • 另外,for j in range (1,5): 从未使用过?或者至少你不在任何地方使用j,并且标签缩进在多个地方完全错误..

标签: python file loops


【解决方案1】:
import os
f = open("final.txt","a+")
for root, folders, files in os.walk('./path/to/html_files/'):
    for fileName in files:
        fo = open(os.path.abspath(root + '/' + fileName, "r")
        ...

然后您的其余代码会放在那里。

还要考虑(最佳做法)

with open(os.path.abspath(root + '/' + fileName, "r") as fo:
    ...

所以你不要忘记关闭这些文件句柄,因为你的操作系统中允许打开的文件句柄数量是有限的,这将确保你不会误填它。

让你的代码看起来像这样:

import os
with open("final.txt","a+") as f:
    for root, folders, files in os.walk('./path/to/html_files/'):
        for fileName in files:
            with open(os.path.abspath(root + '/' + fileName, "r") as fo:
                ...

另外永远不要替换全局变量名,例如str

str=b.readline();

您的代码行末尾也不需要;,这是 Python.. 我们以舒适的方式编写代码!

最后但并非最不重要..

if(c[0]=="APD ID:"):
if(c[0]=="Name/Class:"):
if(c[0]=="Source:"):
if(c[0]=="Sequence:"):
if(c[0]=="Length:"):
if(c[0]=="Net charge:"):
if(c[0]=="Hydrophobic residue%:"):
if(c[0]=="Boman Index:"):

应该是:

if(c[0]=="APD ID:"):
elif(c[0]=="Name/Class:"):
elif(c[0]=="Source:"):
elif(c[0]=="Sequence:"):
elif(c[0]=="Length:"):
elif(c[0]=="Net charge:"):
elif(c[0]=="Hydrophobic residue%:"):
elif(c[0]=="Boman Index:"):

除非你一路修改c,否则你不会……所以切换!

该死,我只是不断发现有关此代码的更可怕的事情(您显然已经从所有星系的示例中复制粘贴了这些内容......):

您可以将以上所有if/elif/else 压缩成一个if-block:

if(c[0] in ("APD ID:", "Name/Class:", "Source:", "Sequence:", "Length:", "Net charge:", "Hydrophobic residue%:", "Boman Index:")):
    f.write(c[1])
    f.write("#")

另外,在 if 块周围跳过 ( ... ),再次。这是 Python 。我们以舒适的方式编程:

if c[0] in ("APD ID:", "Name/Class:", "Source:", "Sequence:", "Length:", "Net charge:", "Hydrophobic residue%:", "Boman Index:"):
    f.write(c[1])
    f.write("#")

【讨论】:

  • 这将拾取 ./path/to/html_files/ 目录中的所有文件。 OP 只想读取 1-100.htm 文件?
  • @RishabhSagar 可能,卡尔普拉特打败了我。看不到将 100 个 html 文件存储在其他文件所在的目录中的意义,而且此解决方案也适用于其他或随机文件命名约定。
【解决方案2】:

也许一些结构看起来像这样:

# declare main files
bo = open("output.txt" ,"w")
f = open("final.txt","a+")

#loop over range ii = [1,100]
for ii in range(1,101):
    fo = open(str(ii) + ".htm", "r")
    # Run program like normal
    ...
    ...
    ...
    fo.close()
f.close()
bo.close()

【讨论】:

  • Traceback(最近一次调用最后一次):文件“C:\Users\Manish\Dropbox\karabi\work files\new1.py”,第 12 行,在 中 fo = open(str( ii) + ".htm", "r") TypeError: 'str' object is not callable
  • 如果您声明一个名为str 的变量,您将无法调用str() 函数。那是因为您现在有一个具有该名称的局部变量,python 将首先查看。尝试将您的字符串变量 str 重命名为更有意义的名称。
  • 非常感谢。我做到了。
  • @user3455594 没问题的人!记得把我的答案标记为正确! :D
【解决方案3】:

os.listdir 列出特定目录中的所有文件。

正如@Torxed 所指出的,最佳做法是使用 with 子句(这样文件句柄就关闭了)。

您可以像这样查找 .htm 文件:

import os

# Creates a list of 1-100.htm file names
filenames = map(lambda x: str(x) + ".htm", range(1,101))

for file in os.listdir("/mydir"):
    if (file in filenames):
        # Do your logic here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2020-09-29
    相关资源
    最近更新 更多