Python从文件夹的每个.txt文件中读取第5行

2024-09-27 17:49:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个.txt文件(O1testO2testO3testO4test

text of 01test(hello,my,friend,sorry,newbie)
text of 02test(hello,my,friend,sorry,newbie)
text of 03test(hello,my,friend,sorry,noob)
text of 04test(hello,my,friend,sorry,amatuer)

输出txt文件可能如下所示

Newbie
01test
02test
Noob
O3test
Amatuer
O4test

正如你所看到的,我需要写一个文件名和第xx行文字,再写一次文件名和第xx行文字,但如果第xx行与前一行相同,则继续下一行

我试过一些东西,但现在我卡住了

import os
for root, dirs, files in os.walk("C:\\Users\\42077\\Desktop\\test\\"):
    for file in files:
        if file.endswith(".txt"):

             with open("C:\\Users\\42077\\Desktop\\test\\!output.txt", "a") as f: as f
                 f.write(os.path.join( file)+"\n")

Tags: 文件oftextfriendtxthelloos文件名
1条回答
网友
1楼 · 发布于 2024-09-27 17:49:03

如何阅读第五行:打开文件,在数数行的同时在行上循环;到第五站时停车

def get_nth(filename, n):
    """
    Return the nth line from filename
    """
    with open(filename) as lines:
        for idx, line in enumerate(lines, 1):
            if idx == n:
                return line.rstrip('\n')
    raise ValueError('file %s only has %i lines' % (filename, idx))

如果文件的行数较少,该怎么办?我决定提出一个错误,但不同的设计肯定是可能的

要组织一组值的结果以及它们所在的文件,请使用dict列表

import glob
from collections import defaultdict

where = defaultdict(list)
for filename in glob.glob('*test'):
    where[get_nth(filename, 5)].append(filename)

在结果dict上循环并打印结果应该相当明显;我把这个留作练习

相关问题 更多 >

    热门问题