首页 > 解决方案 > 在 Python 中验证 txt 文件 (tsv) 的前 3 行

问题描述

我一直在尝试为上传到我的环境的 txt 文件构建验证规则。这些文件是制表符分隔的,我需要验证格式如下的前 3 行:

## This Text Here 
## This Text Here
## This Text Here

我需要建立一个通过失败验证。到目前为止,我已经尝试使用 python 中的内置 csv 函数来执行此操作,但没有成功。将不胜感激任何关于最佳路线的建议。

标签: pythoncsvdataframevalidation

解决方案


尝试这个:

### 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


推荐阅读