close

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

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper Error Occurs?

Today I get the following error TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper in python.

How To Solve TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper Error ?

  1. How To Solve TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper Error ?

    To Solve TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper Error You're passing open an already opened file, rather than the path of the file you created.

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

    To Solve TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper Error You're passing open an already opened file, rather than the path of the file you created.

Solution 1

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)

Solution 2

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.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read