繁体   English   中英

将标签txt转换为CSV批处理

[英]Convert tab txt to CSV batch

我正在尝试编写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)

添加额外的换行符通常是由于打开文件时未指定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()函数来避免循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM