假设我有一个包含以下内容的文本文件
fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk
Run Code Online (Sandbox Code Playgroud)
现在我需要编写一个Python代码,它将读取文本文件并将内容复制到Start和end之间另一个文件.
我写了以下代码.
inFile = open("data.txt")
outFile = open("result.txt", "w")
buffer = []
keepCurrentSet = True
for line in inFile:
buffer.append(line)
if line.startswith("Start"):
#---- starts a new data set
if keepCurrentSet:
outFile.write("".join(buffer))
#now reset our state
keepCurrentSet = False
buffer = []
elif line.startswith("End"):
keepCurrentSet = True
inFile.close()
outFile.close()
Run Code Online (Sandbox Code Playgroud)
我没有按预期获得所需的输出我刚刚开始我想要得到的是开始和结束之间的所有线路.不包括开始和结束.
ins*_*get 36
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
continue
elif line.strip() == "End":
copy = False
continue
elif copy:
outfile.write(line)
Run Code Online (Sandbox Code Playgroud)
如果文本文件不一定很大,则可以获取文件的全部内容,然后使用正则表达式:
import re
with open('data.txt') as myfile:
content = myfile.read()
text = re.search(r'Start\n.*?End', content, re.DOTALL).group()
with open("result.txt", "w") as myfile2:
myfile2.write(text)
Run Code Online (Sandbox Code Playgroud)
我不是 Python 专家,但是这段代码应该可以完成这项工作。
inFile = open("data.txt")
outFile = open("result.txt", "w")
keepCurrentSet = False
for line in inFile:
if line.startswith("End"):
keepCurrentSet = False
if keepCurrentSet:
outFile.write(line)
if line.startswith("Start"):
keepCurrentSet = True
inFile.close()
outFile.close()
Run Code Online (Sandbox Code Playgroud)
使用itertools.dropwhile,itertools.takewhile,itertools.islice:
import itertools
with open('data.txt') as f, open('result.txt', 'w') as fout:
it = itertools.dropwhile(lambda line: line.strip() != 'Start', f)
it = itertools.islice(it, 1, None)
it = itertools.takewhile(lambda line: line.strip() != 'End', it)
fout.writelines(it)
Run Code Online (Sandbox Code Playgroud)
更新:正如inspectorG4dget所说,以上代码在第一个块上进行了复制。要复制多个块,请使用以下命令:
import itertools
with open('data.txt', 'r') as f, open('result.txt', 'w') as fout:
while True:
it = itertools.dropwhile(lambda line: line.strip() != 'Start', f)
if next(it, None) is None: break
fout.writelines(itertools.takewhile(lambda line: line.strip() != 'End', it))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37100 次 |
| 最近记录: |