[英]Can a text file and a json file be used interchangeably? And if so how can I use it in python?
Question: I was wondering if JSON and txt files could be used interchangeably in python.问:我想知道 JSON 和 txt 文件是否可以在 python 中互换使用。
More Details: I found this on the internet and this on stack overflow to find what a JSON file is but it did not say if json and txt could be used interchangeably ie using the same commands.更多详细信息:我发现这个在互联网上, 这对堆栈溢出找到一个JSON文件是什么,但它并没有说,如果JSON和TXT可以互换,即使用相同的命令一起使用。 For example, can both use the same code
with open('filename')as file:
or does JSON require a different code.例如,可以在
with open('filename')as file:
使用相同的代码with open('filename')as file:
或者 JSON 是否需要不同的代码。 Also if they can be used in the same general manner is linking and using commands for a JSON file and a txt file the same process?此外,如果它们可以以相同的一般方式使用,是否可以将 JSON 文件和 txt 文件的命令链接和使用相同的过程?
OS: windows 10操作系统: Windows 10
IDE: IDLE 64-bit IDE:空闲 64 位
Version: Python 3.7版本: Python 3.7
A .txt
file can contain JSON data, and using open()
in Python can open any file, with any content, and any file extension (granted the user running the code has permissions to do so) .txt
文件可以包含 JSON 数据,在 Python 中使用open()
可以打开任何文件、任何内容和任何文件扩展名(授予运行代码的用户这样做的权限)
It's not until you try to load a non JSON string or file using json.loads
or json.load
, respectively, where the problem starts.直到您尝试分别使用
json.loads
或json.load
加载非 JSON 字符串或文件,问题才开始。
In other words, a file contains binary data.换句话说,文件包含二进制数据。 The data can be represented as a string, that string could be XHTML, JSON, CSV, YAML, whatever, and you must use the appropriate parser to extract the relevant data from that format (but it's not always the file extensions that determine what to use)
数据可以表示为一个字符串,该字符串可以是 XHTML、JSON、CSV、YAML 等等,您必须使用适当的解析器从该格式中提取相关数据(但并不总是文件扩展名决定要使用什么格式)用)
does JSON require a different code
JSON 是否需要不同的代码
It requires another module它需要另一个模块
import json
with open(name) as f:
data = json.load(f)
You can read the raw data out of any file the same way;你可以用同样的方式从任何文件中读取原始数据; the difference is in reading the structure in the data.
区别在于读取数据中的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.