我已经通过以下命令加载了文本文件。我想从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 ...
第二,如何从\n
的每个元素(即每一行)的末尾删除contents
?
谢谢
答案 0 :(得分:2)
使用切片:
文件:
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']
编辑:
如果文本在一行中,则可以将列表转换为字符串,并通过分隔符\n
进行split():
txtfile = open(filepath, "rt")
contents = txtfile.readlines()
print("".join(contents).split(r'\n1')[1:])
答案 1 :(得分:1)
尝试:
txtfile = open(filepath, "rt")
txtfile.readline() # Discard first line
contents = txtfile.read()
答案 2 :(得分:0)
尝试:
txtfile = open(filepath, "rt")
contents = txtfile.read()
#split it and join only the items after it
after = ''.join(contents.split(r'\n1')[1:])
答案 3 :(得分:0)
您只需在next
上使用fd
跳过标题,
>>> with open(filepath, "rt") as textfile:
... next(textfile) # Discard first line
... contents = txtfile.read()
答案 4 :(得分:0)
在您的示例中,这可能有效:
import re
#your code
content = re.sub( ".*?\n1", "", content, 1 ) #Replace the first occurance of "[Anything]\n1" with ""