This is an explanation of the video content.
 Everything to games
Let's make life more fun, so we convert everything to games.
27

 |   | 

Use Python get data from xlsx file

To achieve this task, you can use the pandas library to read the Excel file and then convert the data into the desired JSON format. Below is a step-by-step guide and the corresponding Python code to accomplish this:

  1. Install the required libraries: Make sure you have pandas and openpyxl installed. You can install them using pip if you haven’t already:

    pip install pandas openpyxl
    
  2. Read the Excel file: Use pandas to read the Excel file and convert it to a DataFrame.

  3. Transform the data: Modify the DataFrame to match the desired JSON structure.

  4. Save to JSON file: Write the transformed data to a JSON file.

Here is the complete Python code to achieve this:

import pandas as pd

# Step 1: Read the Excel file
file_path = 'mobile.xlsx'
df = pd.read_excel(file_path)

# Step 2: Transform the data
# Initialize an empty list to store the transformed data
transformed_data = []

# Iterate over each row in the DataFrame
for index, row in df.iterrows():
    # Create a dictionary for each row with the desired structure
    transformed_row = {
        "mobile_id": index + 1,  # Assuming mobile_id starts from 1
        "mobile": None,  # As per the desired JSON format
        "code": 0,  # As per the desired JSON format
        "province": row['Province'],
        "city": row['City'],
        "sp": row['SP'],
        "is_updated": 1  # As per the desired JSON format
    }
    # Append the dictionary to the list
    transformed_data.append(transformed_row)

# Step 3: Save the transformed data to a JSON file
output_file = 'mobile.json'
with open(output_file, 'w', encoding='utf-8') as json_file:
    import json
    json.dump(transformed_data, json_file, ensure_ascii=False, indent=4)

print(f"Data has been successfully written to {output_file}")

Explanation:

  1. Reading the Excel file: The pd.read_excel(file_path) function reads the Excel file into a DataFrame.
  2. Transforming the data: We iterate over each row in the DataFrame and create a dictionary for each row that matches the desired JSON structure.
  3. Saving to JSON: We use the json.dump() function to write the list of dictionaries to a JSON file.

Notes:

  • The mobile_id is generated based on the row index, starting from 1.
  • The mobile field is set to None as per the desired JSON format.
  • The code and is_updated fields are set to 0 and 1, respectively, as per the desired JSON format.

Make sure the Excel file mobile.xlsx is in the same directory as your script, or provide the full path to the file. The resulting mobile.json file will be created in the same directory.

27 ⚙️Backend ↦ Python从0到1手把手教程 __ 412 字
 Python从0到1手把手教程 #5