Justme
Justme

Reputation: 85

Combine two Python codes

I am very new in python, but I have been able to make few useful python codes (at least useful for my work). I would like to combine two of my codes, but I have a hard time making it work, I think I am completely lost in how the code should looks like.

The first code basically takes a file, read it, extract to columns from it, and then write the columns in a new file. I repeat this with several files:

import sys
import re

filetowrite = sys.argv[1]
filetoread = sys.argv[2]

newfile = str(filetowrite) + ".txt"

openold = open(filetoread,"r")
opennew = open(newfile,"w")

rline = openold.readlines()

number = int(len(rline))
start = 0

for i in range (len(rline)) :
    if "2theta" in rline[i] :
        start = i

opennew.write ("q" + "\t" + "I" + "\n")
opennew.write ("1/A" + "\t" + "1/cm" + "\n")
opennew.write (str(filetowrite) + "\t" + str(filetowrite) + "\n")

for line in rline[start + 1 : number] :
    words = line.split()
    word1 = (words[1])
    word2 = (words[2])
    opennew.write (word1 + "\t" + word2 + "\n")

openold.close()
opennew.close()

The second code takes the new previously created files and combine them in a way in which the columns are next to each other in the final file.

import sys
from itertools import izip

filenames = sys.argv[2:]

filetowrite = sys.argv[1]

newfile = str(filetowrite) + ".txt"
opennew = open(newfile, "w")

files = map(open, filenames)

for lines in izip(*files):
    opennew.write(('\t'.join(i.strip() for i in lines))+"\n")

Any help in how to proceed to make a single code out of these two codes is highly appreciated.

All the best

Upvotes: 0

Views: 8308

Answers (1)

Makoto
Makoto

Reputation: 106480

Make each file into a function in one larger file, then call the functions as necessary. Make use of __main__ to do that.

import sys
import re
from itertools import izip

def func_for_file1():
    # All of the code from File 1 goes here.

def func_for_file2():
    # ALl of the code from File 2 goes here.

def main():
   # Decide what order you want to call these methods.
   func_for_file1()
   func_for_file2()

if __name__ == '__main__':
   main()

Upvotes: 2

Related Questions