-1

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)
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
sajid
  • 1

1 Answers1

0

It's unclear what exactly is your problem or what you have actively tried so far.

Looking at the code you supplied, there are somethings to point out:

  1. Since you are iterating over lines obtained using readlines(), they already contain line breaks. Therefore when writing to file, you should use simply write() instead of writelines(), unless you want duplicated line breaks.

  2. If the desired output is each function on a different file, you should create a new file each time you find an occurrence of "def". You could simply use a counter and increment it each time to create unique filenames.

  3. Always make sure you are correctly dealing with files (opening and close or using with statement). In your code, it seems that file would no longer be opened in your else statement.

Another possible solution, based on Extract functions from python file and write them to other files (not sure if duplicate, as I am new here, but very similar question), would be:

Instead of reading each line of the file, you could read the entire file and then split it by "def" keyword.

  1. Read the file to a String.
  2. Split the string by "def" (make sure you don't end up without the "def" words) into a list.
  3. Ignore the first element, since it will be everything before the first function definition, and iterate over the remaining ones.
  4. Write each of those Strings (as they will be the function defs you want) into a new file (you could use a counter and increment it to produce a different name for each of the files).

Follow this steps and you should achieve your goal.

Let me know if you need extra clarification.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jmiguel
  • 349
  • 1
  • 9