1

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.

4
  • You are not joining rows together. Your list comprehension should be inside your join(). Commented Jan 17, 2021 at 18:08
  • Can you post an example,please? Commented Jan 17, 2021 at 18:30
  • Untested: my_output_file.write(',', join([ row for row in csv.reader(my_input_file)]) Commented Jan 17, 2021 at 18:35
  • I get an error Syntax Fault Commented Jan 17, 2021 at 18:53

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.