D.Fig
D.Fig

Reputation: 149

How to put output data into directory specified in path1?

I want to write my output files into directory added to path1. But when I try to do that error occurs.

import os
import sys

path = 'ODOGS/LAB'
path1= 'ODOGS/lab_res_voiced'

for file in os.listdir(path):
    current = os.path.join(path, file)
    name_output=file #name of the current file must be the same for the output file


    index_list_B = []
    line_list_B = []
    line_list_linije = []

    with open(current) as f1:
         for index1, line1 in enumerate(f1):
            strings_B = ("p","P","t","T") #find lines which contain this str
            line_list_B.append(line1) #put the line in line_list_B
            if any(s in line1 for s in strings_B):
                line_list_linije.append(line1)
                print(line_list_linije)
                index_list_B.append(index1) #positions of lines

    with open(path1.join(name_output).format(index1), 'w') as output1:
             for index1 in index_list_B:
                 print(line_list_B[index1])                
                 output1.writelines([line_list_B[index11],
                                     line_list_B[index1],','])

This code goes trough the text files in 'ODOGS/LAB' directory and searches if there are lines that contain ceratain strings. After it finds all lines which match the condition, it needs to write them in new file but with the same name as input file. That part of a code works just fine.

I want to put all of output files into another directory path1 but the part of with statement doesn't work.

I get an error:

FileNotFoundError: [Errno 2] No such file or directory: 'sODOGS/lab_res_voicedzODOGS...

It works when the with statement is:

with open(name_output.format(index1), 'w') as output1:

but then I get all the files in the root folder which I don't want. My question is how can I put my output files into directory in path1?

Upvotes: 0

Views: 56

Answers (1)

Zev Averbach
Zev Averbach

Reputation: 1134

There's an error in forming the output path:

Instead of

with open(path1.join(name_output).format(index1), 'w') as output1:

you want

with open(os.path.join(path1, name_output), 'w') as output1:

Upvotes: 2

Related Questions