Python 复制另一个文本文件中字符串之前的所有行
Python copy all lines before string in another text file
我已经在我的代码中堆叠,我想从这个代码打开已经存在的带有大文本(输入)的文件,阅读它并且如果行包含“***”然后复制它之前的行并粘贴到另一个文件(输出)。
例如,我的输入文件如下所示:
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
我已经在我的代码中堆叠,我想从这个代码打开已经存在的带有大文本(输入)的文件,阅读它并且如果行包含“***”然后复制它之前的行并粘贴到另一个文件(输出)。
例如,我的输入文件如下所示:
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