trouselife
trouselife

Reputation: 969

Python - reading a single file, extracting data from it, and then writing it to many files

I am trying to read 1 file, parse data from it then write each parsed column to another file in a different directory. Here is my code:

os.makedirs("new_directory")
my_file = open("original_file.txt", "r+")
output = "new_file.txt"
outputfile = open("new_directory/"+output, "w")
num = 3

for line in my_file:
    line = line.split("\t")
    sample = line[num]
    lst = line[1] + "\t" + line[2] + "\t" + sample + "\n"
    outputfile.write(lst)

This is as far as I have got. I want to write multipe output files with different information from the original file, and save them all in the new directory. How can I write a loop to change the output file name each time - I was trying to increment 'num' and then maybe add it to the output variable:

output = "new_file" + num + ".txt"
outputfile = open("new_directory/"+output, "w")

Or something like this. Is there a better way?

Upvotes: 0

Views: 60

Answers (1)

Saeid
Saeid

Reputation: 4265

You can create a list of files

outputfiles = []    
for num in range(number_of_output_files):     
    output = "new_file" + str(num) + ".txt" # or "new_file%d.txt"%(num)
    outputfiles.append( open("new_directory/"+output, "w") )

for num in range(number_of_output_files):     
    outputfiles[num].write( 'something\n' )

for num in range(number_of_output_files):     
    outputfiles[num].close()

Upvotes: 1

Related Questions