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

标签 html performance python

我想以最高效的方式访问存储在目录 (~20) 中的 .txt 文件 (~1000) 中的每个值 (~10000)。抓取数据后,我想将它们放在 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() 并阅读了一些关于哈希表的内容,而是在挖洞之前询问专家。

感谢您的宝贵时间! /卡尔

最佳答案

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()

关于html - 访问文件结构中数据的pythonic方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7106596/

相关文章:

javascript - OnMouseScroll 自增一个变量 JS

html - 如何在&lt;input type ="file"/>中显示文件路径?

html - 标题位置上的图像在 chrome 中带有边框并且在 firefox 中运行良好

performance - 在 Perl 中更快地搜索文件

python - 使用 Keras 创建平方函数估计器

javascript - 通过webrtc传递上传的图片 - pubnub

arrays - Ruby 中哪个更快, `arr += [x]` 或 `arr << x`

ios - 在 Swift 中将静态函数声明为私有(private)时的性能和安全问题

python - 从 Node 中杀死 Python 进程并不会杀死 Python 的子进程(子进程是 ffmpeg.exe)

python - 如何使用 Google Appengine 在 url 中使用 ';'(分号)