3

i have writted a python file with a lot of functions and i decided i want to split all of them to diffrent files with their names and with the same imports.

the code looks something like this:

import....

class TestExtractors(unittest.TestCase):

    def test_icloud(self):...
    def test_gogoair(self):...
    def test_touchofmodern(self):...

i have over 100 functions in the same file so it became too long. i would like to split each function to a file with the same import, and class TestExtractor(unittest.TestCase): and i would like the filename to be the name of the function(without (self)).

thank you for any advice!

Viktor Malyi
  • 2,298
  • 2
  • 23
  • 40
Gilad
  • 97
  • 2
  • 9
  • 1
    Since these funtions are part of class, you can't really move them elsewhere. What would you exactly like to do? – Neithrik Apr 14 '15 at 08:24
  • hey Riko, i don't mind copying the class all over again, the functions are not bond to each other and they not need each other to work. they only need the class TestExtractors. so every file should contain the `import`,`class`, and `def` – Gilad Apr 14 '15 at 08:30
  • Alright. So if I understand right, you want to write script that will do that automatically? – Neithrik Apr 14 '15 at 08:32
  • I see. Thank you for clarifying. Will write answer in a bit. – Neithrik Apr 14 '15 at 08:40

1 Answers1

2

Make new script "split.py" or something. This script should do:

1) Open the above file as string. How do I read a text file into a string variable in Python

2) Split with argument " def ". Now you will have list of strings, lets call that list L.

3) Ignore first element in L and iterate over all others.

4) For each that string, lets call it S, open new file and write into it:

import....

class TestExtractors(unittest.TestCase):

Below that write string S.

Let me know if I need to clarify any step.

Community
  • 1
  • 1
Neithrik
  • 2,002
  • 2
  • 20
  • 33
  • how do i tell the `open()` to `.split` by `def`? – Gilad Apr 14 '15 at 09:02
  • ok, i managed to do that. but i don't know how to make the script name the file like the function. – Gilad Apr 14 '15 at 09:17
  • To do that you will need to parse that string S. If you simply find index of first "(" with .find than you can get out name. – Neithrik Apr 14 '15 at 09:21
  • `with open ("laknertest.py") as myfile: data=myfile.read().replace('\n', '') l=data.split('def') for s in l[1:]: with open("/home/superfly/Documents/split/{0}.html".format(s),"w") as f: f.write(s)` came up with this, don't know how to continue – Gilad Apr 16 '15 at 13:49
  • You are right track. Just play with code a bit and you'll solve it :) – Neithrik Apr 16 '15 at 13:52