首页 > 解决方案 > Python将文件写入目录

问题描述

我正在尝试将文件写入 python 中的目录。文件名存储在 JSON 对象中。找到这个文件名后,我将它与另一个目录中的一堆图像匹配。

如果匹配,我想将这些图像写入不同的目录。

这是我到目前为止所拥有的:

# 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

使用这种方法,我收到写入目录的错误:

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

我不确定我做错了什么。谁能纠正我?似乎是一个足够简单的问题。(ps 为可怕的 3 个嵌套 for 循环道歉)

TLDR 试图将找到的文件名写入新测试目录。

谢谢

标签: pythonpython-3.xpython-2.7

解决方案


file = open(file_path, 'w')

崩溃是因为你给它一个来自这里的列表:

file_path = os.listdir(directory)

一个快速的解决办法是:

file_path = os.listdir(directory)[0]

只得到第一个,但我不确定那是你真正想要的......


如果目录已经是这样的路径: r"D:\test" 你可以这样做:

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

推荐阅读