gpt4 book ai didi

python - 读入 python 后从文本文件中删除第一行标题

转载 作者:太空宇宙 更新时间:2023-11-04 11:22:13 25 4
gpt4 key购买 nike

我已经通过以下命令加载了文本文件。我想从 contents 中删除由 \n 分隔的第一行标题行。怎么做?

txtfile = open(filepath, "rt")
contents = txtfile.read()
contents
'Label Volume(voxels)SurfArea(mm^2) Eccentricity Elongation Orientation Centroid Axes Length Bounding Box \n 1 148766 ...

其次,如何去掉contents的每个元素(即每一行)末尾的\n

谢谢

最佳答案

使用切片:

文件:

Label  Volume(voxels)SurfArea(mm^2) Eccentricity   Elongation     Orientation    Centroid                      Axes Length                   Bounding Box                  \n1
148766

因此:

txtfile = open(filepath, "rt")
contents = txtfile.readlines()[1:] # skip the first line
print(contents)

输出:

['148766']

编辑:

如果文本是单行的,可以将list转为字符串,通过分隔符split()\n:

txtfile = open(filepath, "rt")
contents = txtfile.readlines()
print("".join(contents).split(r'\n1')[1:])

关于python - 读入 python 后从文本文件中删除第一行标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com