0

i've got a .txt-file that is structured like that:

.
69427 73 69431
.
.
69420 48 69421
.
.
69421 6 69425
.
.
.
69425 28 69427
.
.

the goal is to cut out specific lines, starting with 69420. Then I need to jump to 69421 and cut this line too. The next line will start with 69425 and so on... Each line, starting with a specific number, is only contained one time within the .txt-file. The file isn't sorted by the first number.

I wrote a short python-script, but it isn't working.

file = open("neu.txt", "r")
neue_suche = ""
start = "69420"


def suche(a):
    for line in file:
        if a in line:
            print(line)         
            next_array = line.split()
            neue_suche = next_array[2]
            suche(neue_suche)

suche(start)
file.close()

My goal is, to call the function recursively with the new number, after splitting the line and writing this new number in a variable. The new number is the new parameter of the function. The problem is, that the search doesn't start from the beginning of the file. That means, that the line "69427 73 69431" wouldn't be found and printed with this script. The script will end, but I know, that not every line that I need is printed.

Does anyone have an idea what the problem is?

Thanks :)

  • 1st. You do nothing with your modified lines. 2nd you cannot iterate a file twice. You might want to read the whole file in once - then operate on the data. You could use a dictionary for that. read each line, store the _full_ line under a key of `full_line.split()[0]`. Use your starting value: (A) use it as kto get the line from the dict. Delete the starting key from the dict. Split the line and take the last element. Use that as new key - start over at (A) until done. Then use dict.values() and write them in a new file. – Patrick Artner Sep 04 '20 at 11:51
  • With python 3.7+ the above approch will be stable in regards to line order when writing it back out from the dict.values() – Patrick Artner Sep 04 '20 at 11:52
  • Hey. Thanks for your answer. I created a dictionary, that worked fine. But I don't know what you mean with (A)? I created a for-loop, iterating through dict.values() , which prints me every line I need. I used an if-condition to print the values, that are needed. But I think here is the same problem as above: my loop-counter iterates through the values only 1 time. – ehehehehehehe Sep 04 '20 at 12:50
  • `delete = []; while True: key = start_value; delete.append(key); new_key = d[key].split(-1); if new_key not in d: break else: key = new_key` ... something like that. ... then `for key in delete: del d[key]` – Patrick Artner Sep 04 '20 at 15:01

0 Answers0