Python Data Handling and Utility Functions

  • Share this:

Code introduction


The function uses CSV and JSON formats for reading and writing data, calculates the area of a circle, lists files and folders in the current directory, generates a random number, searches for numbers in a string, gets the name of the current script, and the current time.


Technology Stack : csv, json, math, os, random, re, sys, time

Code Type : Data processing

Code Difficulty : Intermediate


                
                    
import csv
import json
import math
import os
import random
import re
import sys
import time

def xxx(arg1, arg2, arg3):
    # 创建一个CSV文件,并写入一些数据
    with open('data.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['Name', 'Age', 'City'])
        writer.writerow([arg1, arg2, arg3])

    # 读取CSV文件内容
    with open('data.csv', 'r') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            print(', '.join(row))

    # 将CSV数据转换为JSON格式
    data = {'Name': arg1, 'Age': arg2, 'City': arg3}
    with open('data.json', 'w') as jsonfile:
        json.dump(data, jsonfile)

    # 读取JSON文件内容
    with open('data.json', 'r') as jsonfile:
        print(json.load(jsonfile))

    # 使用math模块计算圆的面积
    radius = float(arg1)
    area = math.pi * radius ** 2
    print(f'The area of the circle with radius {radius} is {area}')

    # 使用os模块列出当前目录下的所有文件和文件夹
    for filename in os.listdir('.'):
        print(filename)

    # 使用random模块生成一个随机数
    random_number = random.randint(1, 100)
    print(f'Random number: {random_number}')

    # 使用re模块查找字符串中的数字
    text = f'{arg1} is a number {arg2}'
    match = re.search(r'\d+', text)
    if match:
        print(f'Number found: {match.group()}')

    # 使用sys模块获取当前执行的脚本名称
    print(f'Current script name: {sys.argv[0]}')

    # 使用time模块获取当前时间
    current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print(f'Current time: {current_time}')