创建一个包含文件名及每个文件前两行的文件夹摘要文本文件

2 投票
4 回答
2329 浏览
提问于 2025-04-16 01:25

我有一个文件夹,里面有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这个属性。请帮帮我,提前谢谢!

4 个回答

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

文件对象有一个叫做 next() 的方法,而不是 nextline()

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),你可以通过这个对象手动读取文件中的行。

撰写回答