0

I have multiple .txt files (O1test, O2test, O3test, O4test)

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)

Output txt file may looks like this

Newbie
01test
02test
Noob
O3test
Amatuer
O4test

As you can see I need to write a name of file and xxth line of text and again name of file and xxth line of text but if xxth line is the same as previous go next.

I've tried something but now I'm stuck.

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")
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Going forward, please keep yourself to one question per question. See also [Stack Overflow homework FAQ.](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – tripleee Feb 21 '21 at 13:02

1 Answers1

0

How to read the fifth line: Open the file, loop over the lines while counting them; stop when you reach the fifth.

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

What should happen if the file has fewer lines? I decided to raise an error, but different designs are certainly possible.

To organize the results for a set of values and the files they were found in, use a dict of lists;

import glob
from collections import defaultdict

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

Looping over the resulting dict and printing the results should be fairly obvious; I'm leaving this as an exercise.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thank you @tripleee for help. But you dont get my issue. If you can look at my output i need something different... – Dan Šustai Feb 21 '21 at 13:16
  • *"Looping over the resulting `dict` and printing the results should be fairly obvious; I'm leaving this as an exercise."* Is there a particular aspect of this which is challenging for you? – tripleee Feb 21 '21 at 14:41