结合两个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")
任何帮助如何继续使这两个代码中的单一代码是高度赞赏。
所有最优秀的
答
使每个文件到一个函数在一个较大的文件,然后根据需要调用的函数。利用__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()
请对上面的问题内联代码,不要使用链接! – 2013-03-03 20:35:14