结合两个Python代码

结合两个Python代码

问题描述:

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

任何帮助如何继续使这两个代码中的单一代码是高度赞赏。

所有最优秀的

+2

请对上面的问题内联代码,不要使用链接! – 2013-03-03 20:35:14

使每个文件到一个函数在一个较大的文件,然后根据需要调用的函数。利用__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() 
+0

真诚,感谢您的帮助。但是,我仍然有一个问题。由于这两个代码都包含以特定顺序给出的参数,因此在组合代码中如何工作?谢谢 – Justme 2013-03-05 02:33:07

+0

真诚,我尝试了你的建议,但我可以让它工作。太多不同的错误 – Justme 2013-03-05 03:34:50

+0

我没有看到保留文件在方法中执行的执行顺序的问题。这应该会给你完全相同的表现,除非你正在做其他花哨的东西。我所做的是提取文件的流程,并应该工作。确保你将这些文件独立完成之前,将它们拉入方法中。 – Makoto 2013-03-05 03:41:19