2010-07-16 88 views
2

我有一个包含评分信息的260多个文本文件的目录。我想创建一个包含文件名和每个文件的前两行的所有这些文件的摘要文本文件。我的想法是分别创建两个列表并“压缩”它们。但是,我可以获取文件名列表,但无法将文件的前两行添加到附加列表中。这是我到目前为止的代码:创建文件夹的摘要文本文件,每个文件的前两行

# creating a list of filename 
for f in os.listdir("../scores"): 
    (pdb, extension) = os.path.splitext(f) 
    name.append(pdb[1:5]) 

# creating a list of the first two lines of each file 
for f in os.listdir("../scores"): 
    for line in open(f): 
     score.append(line) 
     b = f.nextline() 
     score.append(b) 

我得到一个错误的str没有属性nextline。请提前帮助,谢谢。

+1

为什么不把文件名和前两行放在同一个循环中? – 2010-07-16 19:39:52

+0

它不是python,所以我不会把它放在答案中,但你最好的(假设unix)是使用bash命令:'head -2 ../scores/*> summary.txt' – perimosocordiae 2010-07-16 19:50:35

回答

4

你得到的问题是从分数上使用文件迭代(for line in f)文件试图采取多条线路在同一时间的结果。这里有一个快速修复(几种方式做到这一点的,我敢肯定):

# creating a list of the first two lines of each file 
for f in os.listdir("../scores"): 
    with open(f) as fh: 
     score.append(fh.readline()) 
     score.append(fh.readline()) 

with声明将关闭该文件为你大功告成后的护理,和它给你一个文件句柄对象(fh),您可以从手动抓取线条。

+0

谢谢!工作了一段时间,现在工作我把两个部分置于同一个循环中。干杯! – 2010-07-16 20:00:02

1

文件对象的方法不是nextline()。从大卫和perimosocordiae

0

合并评论答案:

from __future__ import with_statement 
from itertools import islice 
import os 
NUM_LINES = 2 
with open('../dir_summary.txt','w') as dir_summary: 
    for f in os.listdir('.'): 
    with open(f) as tf: 
     dir_summary.write('%s: %s\n' % (f, repr(', '.join(islice(tf,NUM_LINES))))) 
0

这里是我的,也许更老式的版本更容易换行重定向打印。

## written for Python 2.7, summarize filename and two first lines of files of given filetype 
import os 
extension = '.txt' ## replace with extension of desired files 
os.chdir('.') ## '../scores') ## location of files 

summary = open('summary.txt','w') 
# creating a list of filenames with right extension 
for fn in [fn for fn in os.listdir(os.curdir) if os.path.isfile(fn) and fn.endswith(extension)]: 
    with open(fn) as the_file: 
     print >>summary, '**'+fn+'**' 
     print >>summary, the_file.readline(), the_file.readline(), 
     print >>summary, '-'*60 
summary.close() 
## show resulta 
print(open('summary.txt').read()) 
相关问题