Python Forum

Full Version: splitting file into multiple files by searching for string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody,

I got a backup of a bunch of chess games (from chess.com) I played with a friend of mine and wanted to save them as individual files. Now I only have a complete file with all games but I noticed, that every individual game begins with the string "[Event "Let's Play!"]".

Now I want to create a python script which checks for the string and saves everything to a file until the string occurs again, but I'm not sure how to do so. I thought of using a for-loop which looks for the string, saves everything to a file (with increasing counter) until the string comes again and the loop repeats.

My first problem is, how take only the "difference" between the string?
Look to see if the line from the file starts with (hint hint) "[Event "Let's Play!"]".
The logic would be something like this:
Output:
output file = None open input file for line in file if line starts with "[Event "Let's Play!"]" if output file close output file open new output file if output file write line to output file close input file close output file
There are also command line tools that will do the job, like awk.
How big is the file with all the games?

You could just load the whole string, split on [Event "Let's Play!"], then you have a list of strings of individual games.

In Python you would need to replace Let's with Let\'s first to escape the apostrophe. ctrl h in a text editor, if you have a text file, quick and easy.

Then take each element in the list and write it to a file, except if it is an empty string.

games = data.split('[Event "Let\'s Play!"]')
Just a suggestion!