简体   繁体   中英

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.

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. For example, can both use the same code with open('filename')as file: or does JSON require a different code. 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?

OS: windows 10

IDE: IDLE 64-bit

Version: 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)

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.

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)

does JSON require a different code

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM