python - 在 Python 中验证 txt 文件 (tsv) 的前 3 行
问题描述
我一直在尝试为上传到我的环境的 txt 文件构建验证规则。这些文件是制表符分隔的,我需要验证格式如下的前 3 行:
## This Text Here
## This Text Here
## This Text Here
我需要建立一个通过失败验证。到目前为止,我已经尝试使用 python 中的内置 csv 函数来执行此操作,但没有成功。将不胜感激任何关于最佳路线的建议。
解决方案
尝试这个:
### it depends on how you open the file but...
# open using with..
with open("test.tsv") as inData:
# split lines on tabs...
allLines = [l.split("\t") for l in inData]
# get the lines in question:
testLines = [l[0] for l in allLines[:3]]
# then you could use assert
for l in testLines:
assert(l.startswith("##"))
# and whatever other validation you need for the string
### you could ad try/except
try:
for l in testLines:
assert(l.startswith("##"))
except AssertionError as e:
print(e, "please use a validated file!")
进一步阅读:https ://www.tutorialspoint.com/python/python_exceptions.htm
推荐阅读
- php - Web 服务器迁移后 LDAP 身份验证不起作用
- javascript - 意外的行为jquery
- javascript - 如何在列表视图 Visual Studio LightSwitch 顶部添加多选复选框
- google-api - 通过日历 api 在特定时间安排谷歌日历邀请
- html - 保存和加载动态创建的可拖动元素的位置(jQuery-UI)
- amazon-web-services - EMR 命令运行程序如何提交作业
- sql - Google Data Studio (BigQuery) - 创建过滤器以按最新时间选择
- itext - ITextSharp v5.5.13.0 XMLWorker 土耳其语字符问题
- c# - 从拆分字符串c#动态创建变量
- featuretools - 升级后运行 Featuretools dfs 时出现“IndexError: Too many levels”