Skip to content
Advertisement

How to save each line of a file to a new file (every line a new file) and do that for multiple original files

I have 5 files from which i want to take each line (24 lines in total) and save it to a new file. I managed to find a code which will do that but they way it is, every time i have to manually change the number of the appropriate original file and of the file i want to save it to and also the number of each line every time.

The code:

JavaScript

I am a beginner at python, and i’m not sure how to make a loop for this, because i assume i need a loop?

Thank you!

Advertisement

Answer

Since you have multiple files here, you could define their names in a list, and use a list comprehension to open file handles to them all:

JavaScript

Since each of these file handles is an iterator that yields a single line every time you iterate over it, you could simply zip() all these file handles to iterate over them simultaneously. Also throw in an enumerate() to get the line numbers:

JavaScript

With three files:

JavaScript

I get the following output:

JavaScript

Finally, since we didn’t use a context manager to open the original file handles, remember to close them after we’re done:

JavaScript

If you have files with an unequal number of lines and you want to create files for all lines, consider using itertools.zip_longest() instead of zip()

Advertisement