8

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 Answers 2

6

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)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks - if this was a function with the file as an input and I had to use a variable name instead of the original file route, what would be the solution?
Edited to include the answer to your second question
1

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.

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.