首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pythonic方式访问文件结构中的数据

pythonic方式访问文件结构中的数据
EN

Stack Overflow用户
提问于 2011-08-18 19:21:54
回答 2查看 86关注 0票数 1

我想以最有效的方式访问存储在目录(~20)中的.txt文件(~10000)中的每个值(~1000)。当数据被抓取时,我想把它们放在一个HTML字符串中。我这样做是为了显示一个HTML页面,其中包含每个文件的表格。伪:

代码语言:javascript
复制
    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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-08-18 19:37:28

代码语言:javascript
复制
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()
票数 3
EN

Stack Overflow用户

发布于 2011-08-18 19:26:39

为什么你会“想象这会永远持续下去”?您正在读取文件,然后将其打印出来--这几乎是您唯一需要做的事情--这就是您要做的全部工作。你可以通过几种方式调整脚本(读取块而不是行,调整缓冲区,打印出来而不是连接,等等),但是如果你不知道你现在花了多少时间,你怎么知道哪种方式更好/更差呢?

首先分析,然后找出脚本是否太慢,然后找一个它慢的地方,然后才优化(或询问优化)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7106596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档