Adreeta Sarmah
Adreeta Sarmah

Reputation: 53

batch process text to csv using python

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

Upvotes: 1

Views: 8730

Answers (1)

alecxe
alecxe

Reputation: 474021

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)

Upvotes: 5

Related Questions