euranoo
euranoo

Reputation: 69

python iterating over files and appending to txt

I'm trying to iterate over files in a folder, but the code is always executed on only one file (there are two files at the moment). The program should open the txt file, convert it to a Python list, and write the list to a new created file (each separately). I can't find the bug alone.

import io
import os

'''printing program directory'''
ANVCONDA_directory = os.path.dirname(os.path.realpath(__file__)) + os.sep

print ANVCONDA_directory


inputdir = ANVCONDA_directory + "TEMP"
print os.listdir(inputdir)


'''counting files in folder'''
path, dirs, files = os.walk(inputdir).next()
file_count = len(files)
print file_count


for filename in os.listdir(inputdir):



#opening txt file to extract data
 with io.open(inputdir + "\\" + filename, "r", encoding="cp1250") as file:
     ocr_results = [line.strip() for line in file]


#spliting into list     
 for line in ocr_results:
    print("[" + line + "]")

#writing list to file
import pickle

with open('outfile' + filename, 'wb') as fp:
    pickle.dump(ocr_results, fp)

Upvotes: 1

Views: 452

Answers (1)

user1890194
user1890194

Reputation:

The indentation for the block of code where you are writing the output seems to be wrong. It should be within the for loop. Since it is currently outside the loop it is only executed after the loop above has ended.

Another point that I would like to mention is that os.listdir includes everything in the folder including sub directories. Maybe you should look at os.isdir if you want to skip directories

Upvotes: 1

Related Questions