NoobHacker
NoobHacker

Reputation: 33

Python write file to directory

I'm trying to write files to a directory in python. The filename is stored in a JSON object. After finding this filename, I match it to a bunch of images in another directory.

If there is a match, I want to write those images to a different directory.

This is what I have so far:

# images is the JSON key which contains the [file_name]
for im in images:
    img_data = im["file_name"]
    # The images are stored in this test directory.
    for root, dirs, files in os.walk("./test/"):
        for filename in files:
            if img_data == filename:
                file_path = os.listdir(directory)
                if not os.path.isdir(directory):
                    os.mkdir(directory)

                file = open(file_path, 'w')
                file.write(filename)
                file.close

With this approach, I'm getting the error for writing to a directory:

File "test-coco.py", line 28, in <module>
    file = open(file_path, 'w')
TypeError: expected str, bytes or os.PathLike object, not list

I'm not sure what I'm doing wrong. Can anyone correct me? Seems like a simple enough problem. (p.s apologies for the horrendous 3 nested for loops)

TLDR trying to write found filename to new-test directory.

Thank you

Upvotes: 1

Views: 363

Answers (1)

Andreas
Andreas

Reputation: 9197

file = open(file_path, 'w')

crashes because you give it a list which comes from here:

file_path = os.listdir(directory)

a quick fix would be:

file_path = os.listdir(directory)[0]

to get only the first one, but I am not sure that is what you actually want ...


If directory is already a path like this: r"D:\test" you can do this:

import os
directory = r"D:\test"

# images is the JSON key which contains the [file_name]
for im in images:
    img_data = im["file_name"]
    # The images are stored in this test directory.
    for root, dirs, files in os.walk("./test/"):
        for filename in files:
            if img_data == filename:
                if not os.path.isdir(directory):
                    os.mkdir(directory)

                file = open(os.path.join(directory, filename), 'w')
                file.write(filename)
                file.close

Upvotes: 1

Related Questions