简体   繁体   English

用逗号将 CSV 文件转换为 pyhton 中的 txt 文件

[英]Convert CSV File to txt file in pyhton with comma

I would like to convert the following csv file to a txt file.我想将以下 csv 文件转换为 txt 文件。

CSV 文件

import csv
csv_file = (r'symbols/Input_weekly_insidebar.csv')
txt_file = (r'symbols/Input_weekly_insidebar.txt')
with open(txt_file, "w") as my_output_file:
   with open(csv_file, "r") as my_input_file:
     [ my_output_file.write(','.join(row)) for row in csv.reader(my_input_file)]
 
     
my_output_file.close()

In the txt output file each symbol should have a comma ',' after the symbol.在 txt output 文件中,每个符号都应在符号后有一个逗号“,”。 Result should be:结果应该是: 在此处输入图像描述

Could you tell me what is wrong in my code?你能告诉我我的代码有什么问题吗? Because the above code produce an output without commas.因为上面的代码产生了一个没有逗号的 output。

Thanks for your support.谢谢你的支持。

Because all rows only contain a single element, no separator will be inserted by ','.join(row) .因为所有行只包含一个元素,所以','.join(row)不会插入任何分隔符。 One simple way to fix it is to just pick the first and only element of each row, which is row[0] .修复它的一个简单方法是只选择每行的第一个也是唯一一个元素,即row[0]

I throw in a next(reader) in order to skip the csv header.为了跳过 csv header,我加入了next(reader)

import csv

csv_file = r'symbols/Input_weekly_insidebar.csv'
txt_file = r'symbols/Input_weekly_insidebar.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)
        next(reader)  # skip the header
        my_output_file.write(','.join(row[0] for row in reader))

Please note that you should not manually call my_output_file.close() because you are already using a with statement to open your files.请注意,您不应手动调用my_output_file.close() ,因为您已经在使用with语句打开文件。 The with statement closes the files for you already. with语句已经为您关闭了文件。

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

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