批处理文本到csv使用python [英] batch process text to csv using python

查看:167
本文介绍了批处理文本到csv使用python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助将一些文本文件转换为csv文件。所有我的文本文件在一个文件夹,我想将它们转换为另一个文件夹的csv文件。单个文件的名称应保持不变。下面是我到目前为止的脚本...转换单个文件工作正常,但工作在一个文件夹中的所有文件是我被困在哪里。任何帮助将不胜感激。

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


推荐答案

glob.glob()非常适合任务。此外,在处理文件时,使用和 c>上下文管理器:

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)

这篇关于批处理文本到csv使用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆