python - 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 试图将找到的文件名写入新测试目录。
谢谢
解决方案
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
推荐阅读
- sqlalchemy - 有没有办法使用 SQLAlchemy 在 Teradata 表上创建主索引?
- c++ - 向量指针奇怪的结果
- python-3.x - python 正则表达式函数用特殊字符分割字符串
- regex - 是否可以匹配字符串中所有出现的模式,具有给定的开始和结束?
- java - 在 linux 上使用 ant 编译时出错:错误的版本 52.0,应该是 50.0
- scala - spark数据框中orderBy的列列表
- postgresql - PostgreSQL 使用 COALESCE 或其他条件表达式来设置字段
- spring - Spring Data MongoDB 与原生 MongoDB
- sql - 需要对查找多个外键值的 SQL 查询使用“VLOOKUP”类型的操作 - SOS
- python - 无法使用 Python 请求将所有数据存储到 Django 数据库中