简体   繁体   中英

Convert CSV File to txt file in pyhton with comma

I would like to convert the following csv file to a txt file.

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. Result should be: 在此处输入图像描述

Could you tell me what is wrong in my code? Because the above code produce an output without commas.

Thanks for your support.

Because all rows only contain a single element, no separator will be inserted by ','.join(row) . One simple way to fix it is to just pick the first and only element of each row, which is row[0] .

I throw in a next(reader) in order to skip the csv header.

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. The with statement closes the files for you already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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