I want to extract each method of a class and write it to a text file. The method can be composed of any length of lines and the input file can contain any number of methods. I want to run a loop that will start copying lines to the output file when it hits the first def
keyword and continue until the second def
. Then it will continue until all methods have been copied into individual files.
Input:
class Myclass:
def one():
pass
def two(x, y):
return x+y
Output File 1:
def one():
pass
Output File 2:
def two(x, y):
return x+y
Code:
with open('myfile.py', 'r') as f1:
lines = f1.readlines()
for line in lines:
if line.startswith('def'): # or if 'def' in line
file = open('output.txt', 'w')
file.writelines(line)
else:
file.writelines(line)