0

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

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

一切顺利

4

1 回答 1

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()
于 2013-03-03T20:39:48.740 回答