python - 使用 python 删除 .dat 文件中的行和列

标签 python linux

我想知道是否有一种简单的方法可以在 python 中删除特定的行和列。如果这是一个微不足道的问题,我们深表歉意。

为了提供一些上下文,我目前正在编写一个脚本来自动执行一系列 linux 命令(特别是 ciao Chandra 望远镜分析命令),其中一部分将特定命令的输出保存到 .dat 文件中。目前输出包含一些我不想要的行和列......

E.G 当前的数据是这样的:

表 block 直方图的数据

--------------------------------------------------------------------------------
ROW    CELL   RCENTRE              RHALFWIDTH           AREA                 COUNTS               SUR_BRI             

     1      1          1.016260150          1.016260150        12.9783552105                    0                    0
     2      1          3.048780450          1.016260150        38.9350656315                  1.0     0.02568378873336
     3      1          5.081300750          1.016260150        64.8917760526                  1.0     0.01541027324001
     4      1          7.113821050          1.016260150        90.8484864736                  1.0     0.01100733802858
     5      1          9.146341350          1.016260150       116.8051968946                    0                    0
     6      1   

-------------------------------------
-------------------------------------

我想删除包含“表 block 直方图数据”和破折号的前几行,以及以“ROW”和“CELL”开头的前两列?

提前致谢

最佳答案

假设您的分隔符是表格,或者您不需要最后的列之间的距离完全相同,并且假设有趣的行以数字开头(如您的示例所示),您可以这样写:

def cutFile(fname, firstWantedColumn):
    """Keep wanted lines and colums: detect lines beginning with number and keep input columns"""
    f=open(fname, "r")
    lf = f.readlines()
    f.close()

    txtOut = ""
    for l in lf:
        if l[0].isdigit(): #detect if first char is a number
            txtOut += "\t".join(l.split()[firstWantedColumn:]) + "\n"
    g = open(".".join(fname.split(".")[:-1]) + "_cutted" + fname.split(".")[-1])
    g.write(txtOut)
    g.close()

cutFile("myFile.dat", 2)

编辑:这是一个暴力解决方案,也许你在谈论一个高级的单线解决方案,但我不确定它是否存在。

关于python - 使用 python 删除 .dat 文件中的行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47814371/

相关文章:

java - Tomcat、WAR 和多个操作系统

c - Linux 发行版之间的二进制兼容性

javascript - 类型错误 : must be string or buffer, 不是实例

python - 调试信息安装语法错误 :invalid syntax

python - 如何在 For 循环 (Python) 的范围内添加 "i"

linux - 仅在linux中发生的opencv undefined reference 错误

c - linux读取系统调用没有得到EOF

linux - 为 Python/Matplotlib 禁用 OpenGL

python - openpyxl 单元格样式未正确报告

python - Python/PySide/PyQt 中的多线程网页抓取