Home python How to create a feature for writing to files (TXT, CSV, JSON)?

How to create a feature for writing to files (TXT, CSV, JSON)?

Author

Date

Category

I write a function for recording Fail JSON file created, but empty. Code:

Def Write_File ():
  With Open ('file_json.json', "w", encoding = "UTF-8") AS File_JSON:
    File_JSON = Create_Randome_Dict_json_File ()
    Data = json.dumps (File_JSON)
  Return Data.
Print (Generate_and_Write_File ())

Earlier I generated: table for writing to the CSV file (create_random_list_csv ()), a dictionary for writing to a JSON file (create_randome_dict_json_file ()) a string to write to the TXT file (Create_randome_txt_data ()) I need Write a function, such as Write_File that takes one parameter – the full path to the file. Depending on the file extension (TXT, CSV, JSON), generate data for recording and write to this file. If the extension does not match the specified, then display the text “Unsupported File Format”

Question: How to fill it and can you make all 1 function, for all files?


Answer 1

  1. did you read the documentation carefully?
    JSON.DUMPs in no way writes to the file. And it serves only to convert Python object in the JSON string.

Recording to the JSON file is performed by JSON.DUMP:

with open ("data_file.json", "w") as write_file:
  JSON.DUMP (DATA, WRITE_FILE)

Well, what is the fact that File_JSON you use first as an object identifier and then override it is not clear how it is a separate question.

  1. function, such as Write_File

It is not clear what is the question. You can merge into one function. This feature must adequately do the following: read data, pass and check the extension. Depending on the result, call one of the three generators and, accordingly, one of three different recording functions.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions