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

标签 python python-2.7 text-files

我已经通过以下命令加载了文本文件。我想从 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/

相关文章:

python - 使用 sklearn 中的 minmaxScalar 缩放 NumPy 数组中具有多个特征的特定特征

python - 在 Python 中将新数字添加到文本文件的列

python - 无法发送请求 : Only unicode objects are escapable. 没有任何类型 <class 'NoneType' >

python - 得到带有奇怪文本的输出,比如☻

python - 当 window = 1 时,pandas 滚动平均值可能存在错误

python-2.7 - Python conda - 如何升级 anaconda 上不可用的包

python - 如何输出多行csv?

c - 将文本文件扫描到链表中

Python测试原始输入,if语句中的原始输入

python - 安装line-in包时出错: NodeJS