[英]Python copy all lines before string in another text file
我已经在我的代码中堆叠,我想从这段代码中打开已经存在大文本(inputt)的文件,读取它,如果行包含“***”,然后复制它之前的行并粘贴到另一个文件中(outputt)。
例如,我的输入文件如下所示:
This is the house
this is the flower
this is a tree
'***'
This is a car
this is an apple
this is the nature
'***'
所以我的目标是复制“***”之前的所有行并将其粘贴到另一个文件中。 所以它可以分成两个文件。 这是我的堆叠代码:
def transform(inputt, outputt):
with open(inputt) as f, open(outputt, "w") as f1:
count = 0
for line in f:
if "***" in line:
f.writelines(deque(f1, count))
else:
count = count + 1
它不是很清楚你想要完成什么。 鉴于您的描述和示例输入文件,听起来您希望将以下内容写入输出:
This is the house
this is the flower
this is a tree
那是对的吗? 如果是这样的话:
def transform(inputt, outputt):
with open(inputt) as f, open(outputt, "w") as f1:
f1.write(f.read().split("***")[0])
这段代码有很多缺陷,但如果没有更好的描述,就很难真正知道你在追求什么。
编辑:鉴于评论中的回应:
def transform(inputt, outputt_base):
with open(inputt, "r") as f:
for count, block in enumerate(f.read().split("***")):
outputt_name = outputt_base + "_{0}.txt".format(count)
with open(outputt_name, "w") as f1:
f1.write(block)
鉴于您的示例输入文件,这将写入两个输出文件:(假设outputt_base
只是字符串output
)
第一个文件: output_1.txt
This is the house
this is the flower
this is a tree
和
第二个文件: output_2.txt
This is a car
this is an apple
this is the nature
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.