[英]Python copy all lines before string in another text file
I have stacked in my code, I want from this code to open file that already exists with huge text (inputt), read it and If line contains "***" then copy lines before it and paste in another file (outputt).我已经在我的代码中堆叠,我想从这段代码中打开已经存在大文本(inputt)的文件,读取它,如果行包含“***”,然后复制它之前的行并粘贴到另一个文件中(outputt)。
My inputt file for example looks like this:例如,我的输入文件如下所示:
This is the house
this is the flower
this is a tree
'***'
This is a car
this is an apple
this is the nature
'***'
So my goal is to copy all lines before "***" and paste it in another file.所以我的目标是复制“***”之前的所有行并将其粘贴到另一个文件中。 So it can be separated into two files.
所以它可以分成两个文件。 Here is my stacked code:
这是我的堆叠代码:
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
Its not really clear what you are trying to accomplish.它不是很清楚你想要完成什么。 Given your description and example input file, it sounds like you would want the following written to outputt:
鉴于您的描述和示例输入文件,听起来您希望将以下内容写入输出:
This is the house
this is the flower
this is a tree
Is that correct?那是对的吗? If so:
如果是这样的话:
def transform(inputt, outputt):
with open(inputt) as f, open(outputt, "w") as f1:
f1.write(f.read().split("***")[0])
This code has a number of flaws, but without a better description it's hard to really know what you're after.这段代码有很多缺陷,但如果没有更好的描述,就很难真正知道你在追求什么。
Edit: Given the response in the comments:编辑:鉴于评论中的回应:
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)
Given your example input file, this would write two output files: (Assuming outputt_base
is just the string output
)鉴于您的示例输入文件,这将写入两个输出文件:(假设
outputt_base
只是字符串output
)
First file: output_1.txt
第一个文件:
output_1.txt
This is the house
this is the flower
this is a tree
and和
Second file: output_2.txt
第二个文件:
output_2.txt
This is a car
this is an apple
this is the nature
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.