Python将文件写入目录 [英] Python write file to directory

查看:54
本文介绍了Python将文件写入目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我目前所拥有的:

# 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

我不确定我做错了什么.任何人都可以纠正我吗?似乎是一个足够简单的问题.(ps 为可怕的 3 个嵌套 for 循环道歉)

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 尝试将找到的文件名写入新测试目录.

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

谢谢

推荐答案

file = open(file_path, 'w')

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

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

file_path = os.listdir(directory)

快速解决方法是:

file_path = os.listdir(directory)[0]

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

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

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

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

这篇关于Python将文件写入目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆