Extract data from a Textfile to filter another Textfile

Hi there!
Working with Python.
I have some huge textfiles and would like to filter them. books.txt has a discription of books in it, genre.txt the all the titles with their genres.

Now I want to just work with the fantasy-genre. Here my code so far:

open(“genrefile.txt”,‘w’).writelines(line for line in open(“genres.txt”) if “fantasy” in line)
open(“finalfile.txt”, ‘w’).writelines(l for l in open(“books.txt”) if open(“genrefile.txt”) in l )

I get the genrefile with just the fantasy-titles, but how do I apply this filtred file to the books.txt?

I tried to make the genrefilde.txt to a String, but when I use
genrestring = open(“genrefile.txt”)
it just delets all the content.

Thanks in advance!

I’m a little unsure what you mean by applying a filtered file to books.txt. You’d need some sort of reference for relating these two files, e.g. if they share details of titles and you could then perform filtering with that information.

I think two of your issues here may relate to the purpose of the open function. It doesn’t read data from a file, it provides a file object which can then be used to work with the file itself (read/write etc. but this is not automatic). You can check the details of what it does in the docs- https://docs.python.org/3/library/functions.html#open

For the actual process of reading and writing to the file have a brief look at this tutorial from the Python docs which should provide you with the relevant information- https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

1 Like