簡體   English   中英

如何將所有 txt 文件從目錄轉換為 csv(創建和寫入文件)並使用 Python 保存它們?

[英]How to convert all the txt file from a dir to csv's (creating and writing to file )and save them using Python?

轉換所有 txt 文件分隔符 '|' 從目錄路徑轉換為 ​​csv 並使用 python 保存在一個位置?

我試過這個硬編碼的代碼。

import csv

txt_file = r"SentiWS_v1.8c_Positive.txt"
csv_file = r"NewProcessedDoc.csv"

with open(txt_file, "r") as in_text:
    in_reader = csv.reader(in_text, delimiter = '|')
    with open(csv_file, "w") as out_csv:
        out_writer = csv.writer(out_csv, newline='')
        for row in in_reader:
            out_writer.writerow(row)

對於路徑位置中的所有 txt 文件,在 dir 路徑中需要具有相同文件名的 csv 文件

pathlib為您提供了大部分文件處理內容:

import csv, pathlib

for path in pathlib.Path(".").glob("*.txt"):
    with path.open() as txtfile, path.with_suffix(".csv").open(mode="w") as csvfile:
        reader = csv.reader(txtfile, delimiter = '|')
        writer = csv.writer(csvfile)
        for row in reader:
            writer.writerow(row)

為了避免輸出文件中的空白,在上面的代碼中添加了換行符參數 import csv, pathlib

for path in pathlib.Path(".").glob("*.txt"):
    with path.open() as txtfile, path.with_suffix(".csv").open(mode="w",**newline=''**) as csvfile:
        reader = csv.reader(txtfile, delimiter = '|')
        writer = csv.writer(csvfile)
        for row in reader:
            writer.writerow(row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM