我有一个包含260多个包含评分信息的文本文件的目录。我想创建所有这些文件的摘要文本文件,其中包含filename和每个文件的前两行。我的想法是分别创建两个列表并“压缩”它们。但是,我可以获取文件名列表,但我无法将文件的前两行放入附加列表中。到目前为止,这是我的代码:
# 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
。请提前帮助,谢谢。
答案 0 :(得分: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
),您可以手动从中获取行。
答案 1 :(得分:1)
文件对象的next()
方法不是nextline()
。
答案 2 :(得分:0)
合并大卫的评论,并从perimosocordiae回答:
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)))))
答案 3 :(得分: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())