1

I need some help with converting a number of text files to csv files. All my text files are in one folder and I want to convert them to csv files into another folder. The names of individual files should remain the same. Below is the script I got so far...converting an individual file works fine but to work on all the files within a folder is where I am stuck. Any help will be appreciated.

import csv
import os

directory = raw_input("INPUT Folder:")
output = raw_input("OUTPUT Folder")

txt_files = directory
csv_files = output

try:

    for txt_file in txt_files:
        in_txt = csv.reader(open(txt_file, "rb"), delimiter = '=')

        for csv_file in csv_files:

            out_csv = csv.writer(open(csv_file, 'wb'))
            out_csv.writerows(in_txt)
except:
    print ()
pppery
  • 3,731
  • 22
  • 33
  • 46

1 Answers1

5

glob.glob() is perfectly suited for the task. Also, use with context manager when working with files:

import csv
import glob
import os

directory = raw_input("INPUT Folder:")
output = raw_input("OUTPUT Folder:")

txt_files = os.path.join(directory, '*.txt')

for txt_file in glob.glob(txt_files):
    with open(txt_file, "rb") as input_file:
        in_txt = csv.reader(input_file, delimiter='=')
        filename = os.path.splitext(os.path.basename(txt_file))[0] + '.csv'

        with open(os.path.join(output, filename), 'wb') as output_file:
            out_csv = csv.writer(output_file)
            out_csv.writerows(in_txt)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thank you so much alecxe. It worked like a charm and also helped me to understand working with multiple files within folders. – Adreeta Sarmah Sep 15 '13 at 20:51