[英]How can I take every 3rd line in a text file, then after taking the value of line 3, take the next one?
[英]How can i take the data between two line in a text file?
我有一个名为 DATA_out 的复杂文本格式输出文件(如下面的示例),我想在文件内的两行(例如值和总计)数据之间获取并另存为 csv。 我用用户输入和结束行做了一个起始行。 当我的代码运行时,它知道从哪里开始写入,但我无法导入结束行(“总计”)。 我只需要添加start_line
和end_line
来re.compile
。
您对使用 USER INPUT 在两行之间获取数据有什么建议吗? 这是我所拥有的。
DATA_out file
values
DATA_LINE 1
DATA_LINE 2
DATA_LINE 3
DATA_LINE 4
total
# Spyder Editor (Python 3.7)
import pandas as pd
import re
start_line = input('Starting:')
end_line = 'total' # end point.
with open('DATA_out.txt','r') as file:
input = file.read()
rexp = re.compile(start_line,re.DOTALL) # need to add between start and end
match = rexp.search(input)
result = '' if match == None else match.group(1)
with open('NEW_FILE.txt','w') as file:
file.write(result)
使用正则表达式,您可以使用'values(.*)total'
或'\\n'
- 'values\\n(.*)\\ntotal'
text = '''DATA_out file
values
DATA_LINE 1
DATA_LINE 2
DATA_LINE 3
DATA_LINE 4
total
'''
import re
result = re.search('values(.*)total', text, re.DOTALL)
if result:
print(result[1])
#print(result.group(1))
如果没有regex
您可以使用find()
来分别查找values
和total
位置,然后用text[start:end]
对其进行切片
text = '''DATA_out file
values
DATA_LINE 1
DATA_LINE 2
DATA_LINE 3
DATA_LINE 4
total
'''
start = text.find('values')
end = text.find('total', start)
if start > -1 and end > -1:
start += len("values")
print(text[start:end])
如果要逐行读取文件。
我使用io.StringIO()
来模拟文件
text = '''DATA_out file
values
DATA_LINE 1
DATA_LINE 2
DATA_LINE 3
DATA_LINE 4
total
'''
import io
#f = open("input.txt")
f = io.StringIO(text)
lines = []
# read till you find line with 'values'
for line in f:
if 'values' in line:
break
# read till you find line with 'values'
for line in f:
if 'total' in line:
break
lines.append(line)
else: # it is `for/else`, not `if/else`
#if not found `total` (so there was no `break`) then clear list
lines = []
if lines:
print("".join(lines))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.