Python 读取文件时如何删除行的第一部分?
我在一个名为“test.txt”的python文档中找到了这个数字列表: 我试图删除每行的第一个数字,并将第二个数字作为整数放入列表中,如下所示:Python 读取文件时如何删除行的第一部分?,python,Python,我在一个名为“test.txt”的python文档中找到了这个数字列表: 我试图删除每行的第一个数字,并将第二个数字作为整数放入列表中,如下所示: [2, 3, 2, 5, 2, 3, 7, 2, 11, 13, 2, 3, 5, 17, 19, 2, 23, 7, 29, 3, 31, 2, 37, 41, 43, 47, 5, 53, 59, 2] 我尝试过以下代码: from inspect import currentframe, getframeinfo frameinfo = g
[2, 3, 2, 5, 2, 3, 7, 2, 11, 13, 2, 3, 5, 17, 19, 2, 23, 7, 29, 3, 31, 2, 37, 41, 43, 47, 5, 53, 59, 2]
我尝试过以下代码:
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe())
with open("test.py", "rt") as openfile:
new_list = []
for line in openfile:
new_list.append(line.rstrip(str(frameinfo.lineno())))
print(new_list)
但它给了我一个错误:
Traceback (most recent call last):
File "fileLocation", line 8, in <module>
new_list.append(line.rstrip(str(frameinfo.lineno())))
TypeError: 'int' object is not callable
回溯(最近一次呼叫最后一次):
文件“fileLocation”,第8行,在
new_list.append(line.rstrip(str(frameinfo.lineno()))
TypeError:“int”对象不可调用
有人能解决这个问题吗?您可以在这里使用
re.sub
:
with open("test.py", "rt") as openfile:
new_list = []
for line in openfile:
new_list.append(re.sub(r'^\d+\s+', '', line))
模式
^\d+\s+
将匹配以行号开头的任何行的前导数字(以及后面的空格)。一个简单的解决方案是使用numpy:
import numpy as np
x = np.genfromtxt('test.py')
new_list = x[:,1]
Tim Biegeleisen的答案应该很有效。
另一种简单的方法是使用
拆分行(在条带化之后),并获取第二个元素
with open("test.py", "rt") as openfile:
new_list = []
for line in openfile:
try:
new_list.append(line.strip().split(' ')[1])
except IndexError:
pass
print(new_list)
这对你有帮助
new_list.append(line.rstrip(str(frameinfo.lineno())).split(" ")[1])
这不是有效的python文档。这是一个错误命名文件中的csv。这是否回答了您的问题?您的文档中是否确实有空行,或者这只是复制文档的结果?
new_list.append(line.rstrip(str(frameinfo.lineno())).split(" ")[1])