簡體   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