4
votes

I am trying to convert a pipe-delimited text file to a CSV file, and then iterate through and print the CSV file. Here is my code:


with open("...somefile.txt", "r") as text_file:
    text_reader = csv.reader(text_file, delimiter='|')
    with open("...somefile.csv", 'w') as csv_file:
        csv_writer = csv.writer(csv_file, delimiter=',')
        csv_writer.writerows(text_reader)

with open (csv_file, 'r') as f:
    reader = csv.reader (f, delimiter=',')
    for row in reader:
        print(row)

However, I am getting this error message :

----> 9 with open (csv_file, 'r') as f:
     10     reader = csv.reader (f, delimiter=',')
     11     for row in reader:

TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

Can anyone explain what this means?

Also, if I were to make this into a function, how could I take in a file name as input and then change the file to add a .csv extension wen converting to a csv file?

Thanks

2

2 Answers

4
votes

You're passing open an already opened file, rather than the path of the file you created.

Replace:

with open (csv_file, 'r') as f:

with

with open ("...somefile.csv", 'r') as f:

To change the extension in a function:

import pathlib

def txt_to_csv(fname):
    new_name = f'{Path(fname).stem}.csv'

    with open(fname, "r") as text_file:
        text_reader = csv.reader(text_file, delimiter='|')
        with open(new_name, 'w') as csv_file:
            csv_writer = csv.writer(csv_file, delimiter=',')
            csv_writer.writerows(text_reader)

    with open (new_name, 'r') as f:
        reader = csv.reader (f, delimiter=',')
        for row in reader:
            print(row)
1
votes

I am not an expert of csv library. However, regarding your other question:

Also, if I were to make this into a function, how could I take in a file name as input and then change the file to add a .csv extension wen converting to a csv file?

Solution:

def converter(input_file_name):
  with open(input_file_name, 'r') as txt_file:
    output_file_name = input_file_name.replace('.txt', '.csv')
    with open(output_file_name, 'w') as csv_file:
      # your logic resides here.