在日常编程工作中,我们常常需要处理各种与时间、数据格式及配置文件相关的问题。本文整理了一系列实用的Python代码片段,涵盖了日期时间转换、数据格式化与转换、获取文件注释以及读取配置文件等内容,助力开发者提升工作效率,轻松应对常见任务。
1. 秒级与毫秒级时间戳获取
-
# 获取当前秒级时间戳
-
def millisecond(add=0):
-
return int(time.time()) + add
-
# 获取当前毫秒级时间戳
-
def millisecond_new():
-
t = time.time()
-
return int(round(t * 1000))
这两个函数分别提供了获取当前时间的秒级和毫秒级时间戳的功能。millisecond()函数允许传入一个可选参数add,用于增加指定的时间偏移量。
2. 当前日期字符串获取
# 获取当前时间日期: 20211009
-
def getNowTime(tianshu=0):
-
shijian = int(time.strftime('%Y%m%d')) - tianshu
-
print(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数据,修复缺失的引号,并将其写入新的文件。源文件与目标文件的路径需替换为实际路径。
4. 将URL查询字符串转为JSON
-
from urllib.parse import urlsplit, parse_qs
-
def 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 os
-
def 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文件,提取每份文件的第
一行注释(以#开头),并将文件名与注释对应关系写入指定的文本文件中。
6.读取配置INI文件
-
import sys
-
import os
-
import configparser
-
class 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"]
ReadConfig类封装了对INI配置文件的读取操作,支持读取sql.ini和hosts.ini文件。通过实例化该类并指定配置文件路径,即可方便地获取所需配置信息。
7.设置全局文件路径
-
import os
-
def 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()函数根据提供的相对路径,结合当前模块的绝对路径,计算出项目根目录下的目标文件或目录的绝对路径,便于在项目中统一管理资源位置。
感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:
这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取