簡體   English   中英

使用 pipe 將 CSV 文件轉換為 Python 中的 txt 文件 - “|”

[英]Convert CSV File to txt file in Python with pipe - "|"

這是我的 csv 文件

.csv 文件

我想使用 Python 將其轉換為以下文本文件(注意最后一列的“|”)

在此處輸入圖像描述

我見過類似的代碼,但它沒有在最后一列的末尾添加 pipe (|)

    import csv

csv_file = 'file_path.csv'
txt_file = 'file_path.txt'
with open(txt_file, "w") as my_output_file:
    with open(csv_file, "r") as my_input_file:
        reader = csv.reader(my_input_file)
        [ my_output_file.write("|".join(row)+'\n') for row in csv.reader(my_input_file)]

謝謝你的幫助!

在您的情況下,分隔符 ('|') 分隔 1 行的每個數據點,在您的情況下,行終止符 ('\n') 分隔每一行,因此在末尾添加另一個 pipe 意味着使用 null 將列添加到所有行值,但如果你想這樣做,在最后一行,替換

[ my_output_file.write("|".join(row)+'\n') for row in csv.reader(my_input_file)]csv.reader(my_input_file)]

[ my_output_file.write("|".join(row+[''])+'\n') for row in csv.reader(my_input_file)]

暫無
暫無

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

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