将标签txt转换为CSV批处理

时间:2018-10-27 18:24:47

标签: python file csv

我正在尝试编写Python脚本,以将源目录中所有制表符分隔的.txt文件批量转换为逗号分隔的.csv文件,但在输出中保留原始文件名。

我对此还很陌生,但是目前我的脚本可以创建新的.csv文件。但是,在我的输出文件的每个数据填充行之间添加了一个空行。我该如何解决这个问题?

import csv
import os

source_path = r"file location"
dest_path = r"file location"

for file in os.listdir(source_path):

    # Get filename without file extension
    filename_no_extension = os.path.splitext(file)[0]

    # Concatenate filename amd paths
    dest_csv_file = str(filename_no_extension) + ".csv"
    dest_file = os.path.join(dest_path,dest_csv_file)
    source_file = os.path.join(source_path,file)

    # Open the original file and create a reader object
    with open(source_file, "r") as infile:
        reader = csv.reader(infile, dialect="excel-tab")
        with open(dest_file, "w") as outfile:
            writer = csv.writer(outfile, delimiter = ',')
            for row in reader:
                writer.writerow(row)

1 个答案:

答案 0 :(得分:0)

添加额外的换行符通常是由于在打开文件时未指定newline=""参数。如果使用Python 2.x,则需要使用rbwb作为文件模式,而不要使用额外的参数:

import csv
import os

source_path = r"file location"
dest_path = r"file location"

for file in os.listdir(source_path):

    # Get filename without file extension
    filename_no_extension = os.path.splitext(file)[0]

    # Concatenate filename amd paths
    dest_csv_file = str(filename_no_extension) + ".csv"
    dest_file = os.path.join(dest_path,dest_csv_file)
    source_file = os.path.join(source_path,file)

    # Open the original file and create a reader object
    with open(source_file, "r", newline="") as infile, open(dest_file, "w", newline="") as outfile:
        reader = csv.reader(infile, dialect="excel-tab")
        writer = csv.writer(outfile)
        writer.writerows(reader)

您还可以通过使用writerows()函数来避免循环。