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