我想以最有效的方式访问存储在目录(~20)中的.txt文件(~10000)中的每个值(~1000)。当数据被抓取时,我想把它们放在一个HTML字符串中。我这样做是为了显示一个HTML页面,其中包含每个文件的表格。伪:
fh=open('MyHtmlFile.html','w')
fh.write('''<head>Lots of tables</head><body>''')
for eachDirectory in rootFolder:
for eachFile in eachDirectory:
concat=''
for eachData in eachFile:
concat=concat+<tr><td>eachData</tr></td>
table='''
<table>%s</table>
'''%(concat)
fh.write(table)
fh.write('''</body>''')
fh.close()一定有更好的方法(我想这可能需要永远)!我已经查看了set(),并阅读了一些关于哈希表的内容,但在挖掘漏洞之前,我更愿意咨询专家。
感谢您的宝贵时间!/Karl
发布于 2011-08-18 19:37:28
import os, os.path
# If you're on Python 2.5 or newer, use 'with'
# needs 'from __future__ import with_statement' on 2.5
fh=open('MyHtmlFile.html','w')
fh.write('<html>\r\n<head><title>Lots of tables</title></head>\r\n<body>\r\n')
# this will recursively descend the tree
for dirpath, dirname, filenames in os.walk(rootFolder):
for filename in filenames:
# again, use 'with' on Python 2.5 or newer
infile = open(os.path.join(dirpath, filename))
# this will format the lines and join them, then format them into the table
# If you're on Python 2.6 or newer you could use 'str.format' instead
fh.write('<table>\r\n%s\r\n</table>' %
'\r\n'.join('<tr><td>%s</tr></td>' % line for line in infile))
infile.close()
fh.write('\r\n</body></html>')
fh.close()发布于 2011-08-18 19:26:39
为什么你会“想象这会永远持续下去”?您正在读取文件,然后将其打印出来--这几乎是您唯一需要做的事情--这就是您要做的全部工作。你可以通过几种方式调整脚本(读取块而不是行,调整缓冲区,打印出来而不是连接,等等),但是如果你不知道你现在花了多少时间,你怎么知道哪种方式更好/更差呢?
首先分析,然后找出脚本是否太慢,然后找一个它慢的地方,然后才优化(或询问优化)。
https://stackoverflow.com/questions/7106596
复制相似问题