结合两个Python代码

时间:2013-03-03 20:32:18

标签: python

我是python中的新手,但我已经能够制作一些有用的python代码(至少对我的工作有用)。我想结合我的两个代码,但我很难让它工作,我想我完全迷失了代码的样子。

第一个代码基本上是一个文件,读取它,从中提取列,然后在新文件中写入列。我用几个文件重复这个:

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()

第二个代码采用先前创建的新文件,并以最终文件中列彼此相邻的方式组合它们。

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")

非常感谢任何有关如何从这两个代码中制作单个代码的帮助。

一切顺利

1 个答案:

答案 0 :(得分:1)

将每个文件放在一个较大文件中的函数中,然后根据需要调用这些函数。利用__main__来做到这一点。

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()