Python代码打开多个文件,然后写入新文件

时间:2013-03-05 03:44:17

标签: python file-io

我制作了一个Python代码,它接受一个文件并从中提取特定信息,然后将其写入新文件。我对几个文件重复了几次。 正如您在代码(下面)中看到的,我有两个参数,第一个是新文件的名称,第二个是要读取的文件,所以我的终端中的命令行看起来像这样“python code.py newfile readfile“。我想以一种我可以一次读写多个文件的方式更改代码,所以我在终端的命令行看起来像“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()

1 个答案:

答案 0 :(得分:1)

正如其他人所指出的那样,您似乎只想循环浏览文件,而不是实际处理所有文件。您可以使用os.listdir()方法获取传入目录中所有文件的列表:

import os;
os.listdir("aDirectoryHere")

它会返回一个你可以循环的列表。

方法文档:http://docs.python.org/2/library/os.html#os.listdir


编辑问题后

您可以遍历sys.argv列表以查找任意数量的参数。

import sys;

for index, arg in enumerate(sys.argv):
    print index, arg;

print "total:", len(sys.argv);

根据您的示例,您可以查看输出文件名的每个索引+2,然后从那里获取+1以获取匹配的输入文件名。

有点偏离主题,但有趣的是,我也遇到了FileInput模块。从来没有见过它,但看起来它也可能有用:http://docs.python.org/2/library/fileinput.html