在日常編程工作中,我們常常需要處理各種與時間、數據格式及配置文件相關的問題。本文整理了一系列實用的Python代碼片段,涵蓋了日期時間轉換、數據格式化與轉換、獲取文件注釋以及讀取配置文件等內容,助力開發者提升工作效率,輕松應對常見任務。
# 獲取當前秒級時間戳def millisecond(add=0): return int(time.time()) + add# 獲取當前毫秒級時間戳def millisecond_new(): t = time.time() return int(round(t * 1000))
這兩個函數分別提供了獲取當前時間的秒級和毫秒級時間戳的功能。millisecond()函數允許傳入一個可選參數add,用于增加指定的時間偏移量。
#獲取當前時間日期: 20211009def getNowTime(tianshu=0):shijian = int(time.strftime('%Y%m%d')) - tianshuprint(shijian)return shijian
getNowTime()函數返回當前日期(格式為YYYYMMDD),并支持傳入參數tianshu以減去指定天數。該函數適用于需要處理日期型數據且僅關注年月日的情況。
3.修復接口返回無引號JSON數據
def json_json(): with open("源文件地址", "r") as f, open("目標文件地址", "a+") as a: a.write("{") for line in f.readlines(): if "[" in line.strip() or "{" in line.strip(): formatted_line = "'" + line.strip().replace(":", "':").replace(" ", "") + "," print(formatted_line) # 輸出修復后的行 a.write(formatted_line + "/n") else: formatted_line = "'" + line.strip().replace(":", "':'").replace(" ", "") + "'," print(formatted_line) # 輸出修復后的行 a.write(formatted_line + "/n") a.write("}")
此函數用于處理從接口復制的未正確格式化的JSON數據,修復缺失的引號,并將其寫入新的文件。源文件與目標文件的路徑需替換為實際路徑。
from urllib.parse import urlsplit, parse_qsdef query_json(url): query = urlsplit(url).query params = dict(parse_qs(query)) cleaned_params = {k: v[0] for k, v in params.items()} return cleaned_params
query_json()函數接收一個包含查詢字符串的URL,解析其查詢部分,將其轉換為字典形式,并清理多值參數,只保留第一個值。
5.文件注釋提取
import osdef get_first_line_comments(directory, output_file): python_files = sorted([f for f in os.listdir(directory) if f.endswith('.py') and f != '__init__.py']) comments_and_files = [] for file in python_files: filepath = os.path.join(directory, file) with open(filepath, 'r', encoding='utf-8') as f: first_line = f.readline().strip() if first_line.startswith('#'): comment = first_line[1:].strip() comments_and_files.append((file, comment)) with open(output_file, 'w', encoding='utf-8') as out: for filename, comment in comments_and_files: out.write(f"{filename}: {comment}/n")# 示例用法get_first_line_comments('指定文件夾', '指定生成文件路徑.txt')get_first_line_comments()函數遍歷指定目錄下的.py文件,提取每份文件的第
import sysimport osimport configparserclass ReadConfig: def __init__(self, config_path): self.path = config_path def read_sqlConfig(self, fileName="sql.ini"): read_mysqlExecuteCon = configparser.ConfigParser() read_mysqlExecuteCon.read(os.path.join(self.path, fileName), encoding="utf-8") return read_mysqlExecuteCon._sections def read_hostsConfig(self, fileName="hosts.ini"): read_hostsCon = configparser.ConfigParser() read_hostsCon.read(os.path.join(self.path, fileName), encoding="utf-8") return read_hostsCon._sections# 示例用法config_reader = ReadConfig('配置文件所在路徑')sql_config = config_reader.read_sqlConfig()hosts_config = config_reader.read_hostsConfig()["hosts"]
import osdef setFilePath(filePath): current_module_path = os.path.dirname(os.path.abspath(__file__)) project_root_path = os.path.dirname(os.path.dirname(current_module_path)) path = os.path.join(project_root_path, filePath.lstrip('/')) return os.path.abspath(path)# 示例用法confPath = setFilePath("地址文件路徑")
setFilePath()函數根據提供的相對路徑,結合當前模塊的絕對路徑,計算出項目根目錄下的目標文件或目錄的絕對路徑,便于在項目中統一管理資源位置。
本文鏈接:http://www.www897cc.com/showinfo-26-81236-0.html接口自動化框架里常用的小工具
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com