以下是一些 Python 3 的实用功能代码合集:
读取文件并返回字符串
def read_file(file_path): with open(file_path, 'r') as f: return f.read()
写入字符串到文件
def write_file(file_path, content): with open(file_path, 'w') as f: f.write(content)
获取文件扩展名
import os def get_file_extension(file_path): return os.path.splitext(file_path)[1]
遍历目录并获取所有文件的路径
import os def get_all_files_in_directory(directory): files = [] for root, dirs, filenames in os.walk(directory): for filename in filenames: file_path = os.path.join(root, filename) files.append(file_path) return files
遍历目录并获取所有子目录的路径
import os def get_all_subdirectories(directory): subdirectories = [] for root, dirs, filenames in os.walk(directory): for dir_name in dirs: dir_path = os.path.join(root, dir_name) subdirectories.append(dir_path) return subdirectories
合并两个字典
def merge_dicts(dict1, dict2): return {**dict1, **dict2}
将列表按照指定大小分割
def split_list(input_list, size): return [input_list[i:i+size] for i in range(0, len(input_list), size)]
获取当前时间戳
import time def get_timestamp(): return int(time.time())
将字典转换为查询字符串
def dict_to_query_string(query_dict): return '&'.join([f'{key}={value}' for key, value in query_dict.items()])
计算两个日期之间的天数
from datetime import datetime def days_between_dates(date1, date2): date1_obj = datetime.strptime(date1, '%Y-%m-%d') date2_obj = datetime.strptime(date2, '%Y-%m-%d') delta = date2_obj - date1_obj return delta.days
希望这些代码可以帮助你在 Python 3 中更轻松地完成一些实用功能。
评论