0

This is likely a fundamental Python question, but I'm stumped (still learning). My script uses Pandas to create txt files from csv cells, and works properly. However, I'd like to write the files to a specific directory, listed as save_path below. However, my efforts to put this together keep running into errors.

Here's my (not) working code:

import os
import pandas as pd

save_path = "C:\users\name\folder\txts"

df= pd.read_csv("C:\users\name\folder\test.csv", sep=",")

df2 = df.fillna('')

for index in range(len(df)):
    with open(df2["text_number"][index] +  '.txt', 'w') as output:
        output2 = os.path.join(save_path, output) # I'm uncertain how to structure or place the os.path.join command.
        output2.write(df2["text"][index])

The resulting error is below:

TypeError: join() argument must be str, bytes, or os.PathLike object, not 'TextIOWrapper'

Thoughts? Any assistance is greatly appreciated.

3
  • 1
    output is your file stream, not your file path. You have to specify the location of your filepath, e.g. the df2["text_number"][index] + '.txt' in your case. Commented Jul 24, 2021 at 19:33
  • 1
    can you tell me what are you trying to achieve from last 3lines? do you want to copy text from one file to other? Commented Jul 24, 2021 at 19:33
  • The script writes a txt file whose name is the cell value in the column "text_number" (text_0, text_1, etc) and whose contents are the cell value for the :column text". Commented Jul 24, 2021 at 19:37

2 Answers 2

1

You need to first generate the file name and then open it in write mode to put the contents.

for index in range(len(df)):
    # create file name
    filename = df2["text_number"][index] +  '.txt'
    # then generate full path using os lib
    full_path = os.path.join(save_path, filename)
    # now open that file, dont forget to use w+ to create the file if it doesn't exist
    with open(full_path, 'w+') as output_file_handler:
        # and write the contents
        output_file_handler.write(df2["text"][index])
Sign up to request clarification or add additional context in comments.

Comments

1

This should work. (But you might want to check out this answer)

for index in range(len(df)):
    filename = df2["text_number"][index] + '.txt'
    fp = os.path.join(save_path, filename)

    with open(fp, 'w') as output:
        output.write(df2["text"][index])

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.