Justme
Justme

Reputation: 85

Python code to open multiple files and then write in new files

I made a Python code that takes one file and extracts particular information from it, and then writes it to a new file. I repeat this several times for several files. As you can see in the code (below), I have two arguments the first one is the name of the new file and the second one is the file to read, so the command line in my terminal looks like this "python code.py newfile readfile". I would like to change the code in a way that I could read and write several files at once, so my command line in terminal would look something like "python code.py newfile1 readfile1 newfile2 readfile2 newfile3 readfile3"...and so on, every file to read will have its own new file to write.

Any help is highly appreciated

Here is my code:

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()

Upvotes: 0

Views: 3423

Answers (1)

mitim
mitim

Reputation: 3201

As others have pointed out, it seems like you want to just loop through your files, rather then actually processing them all at the same time. You can use os.listdir() method to get a list of all the files in a directory you pass in:

import os;
os.listdir("aDirectoryHere")

It'll return a list that you can loop through.

Method documentation: http://docs.python.org/2/library/os.html#os.listdir


After your question edit

You can loop through the sys.argv list to look for any amount of arguments.

import sys;

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

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

Given your sample, you could just look at every index +2 for the output file name, then +1 from there to get the matching input file name.

A bit off topic, but interestingly, I also came across the FileInput module. Had never seen it before, but looks like it may also be useful: http://docs.python.org/2/library/fileinput.html

Upvotes: 1

Related Questions