我编写了一个 Python 代码,它获取一个文件并从中提取特定信息,然后将其写入一个新文件。我对几个文件重复了几次。正如您在代码中看到的(如下),我有两个参数,第一个是新文件的名称,第二个是要读取的文件,所以我终端中的命令行看起来像这样“python code.py新文件读取文件”。我想以一种可以一次读取和写入多个文件的方式更改代码,所以我在终端中的命令行看起来像“python code.py newfile1 readfile1 newfile2 readfile2 newfile3 readfile3”......等等,每个要读取的文件都会有自己的新文件要写入。
非常感谢任何帮助
这是我的代码:
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()