Yvar
Yvar

Reputation: 155

Convert CSV File to txt file in Python with comma

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

CSV File

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: enter image description here

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

Thanks for your support.

Upvotes: 1

Views: 3332

Answers (1)

Lydia van Dyke
Lydia van Dyke

Reputation: 2516

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.

Upvotes: 2

Related Questions