我有一些文件,其中包含以下数据:
begin of file
1,2,3,4,5,6,7
end of file
我想读这个文件,所以我试过了:
filename = open('file','r')
for line in filename:
print line
但现在我需要在txt文件中搜索“开始文件”和“文件结束”等关键字,然后将2个关键字之间的值保存到列表中。 我试过这个:
Listsave = []
filename = open('file', 'r')
for line in filename:
if "begin of file" in line:
listsave.append(line.next())
但它似乎无效。
我该如何处理? 非常感谢
答案 0 :(得分:1)
with open("file") as file:
data = file.read()
result = data.partition("begin of file")[2].rpartition("end of file")[0].strip().split(",")
print result
结果:
['1', '2', '3', '4', '5', '6', '7']
答案 1 :(得分:1)
def getstringbetween(source, first, last):
try:
start = source.index(first) + len(first)
end = source.index(last, start)
return source[start:end]
except ValueError:
return ""
用法:
print getstringbetween("abcdefg", "ab", "fg")
返回:
“CDE”
在您的情况下,将所有文本读取到字符串并调用此函数。如果需要,将结果返回到列表/数组。
答案 2 :(得分:1)
您可以使用以下方法,该方法将使用Python的CSV库将您的行拆分为合适的列。如果需要,这将使得更容易支持不同的分隔符或额外引用。
import StringIO, csv
with open('file.txt', 'r') as f_input:
begin = False
rows = []
for line in f_input:
if line.startswith("end of file"):
break
elif begin:
rows.append(next(csv.reader(StringIO.StringIO(line))))
elif line.startswith("begin of file"):
begin = True
print rows
所以对于以下类型的输入:
stuff
begin of file
1,2,3,4,5,6,7
8,9,10
11,12,13,14,15
end of file
more stuff
它会创建:
[['1', '2', '3', '4', '5', '6', '7'], ['8', '9', '10'], ['11', '12', '13', '14', '15']]
答案 3 :(得分:0)
在这里,试试这个。它标志着我们是否已经超越了起点,并在我们超越终点时中断。
listsave = []
filename = open('file', 'r')
found = False
for line in filename:
if not found:
if 'begin of file' in line:
found = True
else:
if 'end of file' in line:
break
listsave.append(line)
对我来说现在有点早,所以可能有更好的解决方案。
编辑:
稍微清洁一点。
with open('file', 'r') as file:
found = False
saved = []
for line in file:
if not found:
if 'begin of file' in line:
found = True
elif 'end of file' in line:
break
else:
saved.append(line)
答案 4 :(得分:0)
您可以尝试这样的事情:
filename = open('file', 'r')
Listsave = []
subline = ""
for line in filename:
if "begin of file" in line:
continue
elif "end of file" in line:
Listsave.append(subline)
else:
subline += line
print Listsave