You can download this code by clicking the button below.
This code is now available for download.
These functions demonstrate how to use Python's built-in libraries to perform various tasks, including reading and parsing CSV files, writing data to JSON files, generating random strings, traversing directories to find files with a specific extension, replacing strings in files, and printing the system version.
Technology Stack : csv, json, os, random, re, sys
Code Type : Code collection
Code Difficulty : Intermediate
import csv
import json
import os
import random
import re
import sys
def read_and_parse_csv(file_path):
with open(file_path, mode='r', encoding='utf-8') as file:
csv_reader = csv.DictReader(file)
data = [row for row in csv_reader]
return data
def write_data_to_json(data, output_file_path):
with open(output_file_path, mode='w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
def generate_random_string(length):
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(random.choice(letters) for i in range(length))
def filter_files_by_extension(directory, extension):
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(extension):
yield os.path.join(root, file)
def replace_substrings_in_file(file_path, old_string, new_string):
with open(file_path, 'r', encoding='utf-8') as file:
filedata = file.read()
with open(file_path, 'w', encoding='utf-8') as file:
filedata = re.sub(old_string, new_string, filedata)
file.write(filedata)
def print_system_version():
print("Python version:", sys.version)
print("Platform:", sys.platform)