使用python读取文件中的json文件,然后返回与json文件名同名的图片
时间: 2023-02-22 18:58:33 浏览: 105
读取 JSON 文件的方法如下:
1. 打开文件:
```
with open(<文件名>, "r") as file:
data = json.load(file)
```
2. 解析 JSON 数据:
```
import json
with open(<文件名>, "r") as file:
data = json.load(file)
# 在这里可以对数据进行处理
```
回答图片文件名与 JSON 文件名相同,可以通过替换文件名后缀来得到图片文件名:
```
img_file = <文件名>.replace(".json", ".jpg")
```
因此,读取并返回与 JSON 文件名同名的图片的完整代码如下:
```
import json
def read_json_and_return_img(file_name):
with open(file_name, "r") as file:
data = json.load(file)
img_file = file_name.replace(".json", ".jpg")
return img_file
```
相关问题
如何在Python中创建一个类,以便接收用户输入的文件路径,成功读取JSON文件并将其内容转换为字符串,然后将该字符串写入新的文本文件(txt),txt文件与json文件同名且在同一目录下,同时能返回生成的txt文件的路径?
在Python中,你可以通过以下步骤创建一个名为`JsonToText`的类,来实现这个功能:
```python
import json
from pathlib import Path
class JsonToText:
def __init__(self, file_path):
self.file_path = Path(file_path)
if not self.file_path.is_file():
raise ValueError(f"File {file_path} does not exist.")
def read_json(self):
with open(self.file_path, 'r') as json_file:
data = json.load(json_file)
return data
def write_text(self):
text_data = json.dumps(self.read_json(), indent=4) # 将JSON数据转换为格式化的字符串
new_file_name = self.file_path.with_suffix('.txt') # 创建新文件名
with open(new_file_name, 'w') as txt_file:
txt_file.write(text_data)
def generate_txt_file_path(self):
return str(new_file_name)
# 使用示例
try:
user_input = input("Please enter the JSON file path: ")
converter = JsonToText(user_input)
converter.write_text()
print(f"Generated TXT file path: {converter.generate_txt_file_path()}")
except ValueError as e:
print(e)
```
在这个类中,我们首先初始化时检查文件是否存在,接着读取JSON文件,将其转换为字符串,并创建一个新的TXT文件。最后,提供一个方法`generate_txt_file_path`来返回生成的TXT文件的路径。
阅读全文
相关推荐

















