Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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 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)
                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?
– watermelon123
                Mar 16, 2020 at 12:14
  

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.
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.