问题描述
所以我们大多数人都认为它是一个重复的,但不是,所以我想要实现的是假设有一个如下所示的主字符串和其中提到的几个文件,然后我们需要打开这些文件并检查其中是否包含任何其他文件,如果有,我们需要将其复制到我们获取该特定文本的行中.
So as most of us are thinking it's a duplicate which is not, so what I'm trying to achieve is let's say there is a Master string like the below and couple of files mentioned in it then we need to open the files and check if there are any other files included in it, if so we need to copy that into the line where we fetched that particular text.
主字符串:
欢迎
你好吗
文件.txt
一切正常
签名.txt
谢谢
文件.txt
ABCD
EFGH
tele.txt
ABCD
EFGH
tele.txt
tele.txt
IJKL
签名.txt
SAK
输出:
欢迎
你好吗
ABCD
EFGH
IJKL
一切都好
萨克
谢谢
Welcome
How are you
ABCD
EFGH
IJKL
everything alright
SAK
Thanks
for msplitin [stext.split('\n')]:
for num, items in enumerate(stext,1):
if items.strip().startswith("here is") and items.strip().endswith(".txt"):
gmsf = open(os.path.join(os.getcwd()+"\txt", items[8:]), "r")
gmsfstr = gmsf.read()
newline = items.replace(items, gmsfstr)
如何将这些替换项以相同的字符串格式连接起来.
How to join these replace items in the same string format.
另外,关于如何重新迭代相同函数直到没有.txt"的任何想法.因此,一旦连接完成,.txt"中可能还有其他.txt".
Also, any idea on how to re-iterate the same function until there are no ".txt". So, once the join is done there might be other ".txt" inside a ".txt.
提前感谢您的帮助.
推荐答案
适用于任何级别的文件名嵌套的递归方法:
A recursive approach that works with any level of file name nesting:
from os import linesep
def get_text_from_file(file_path):
with open(file_path) as f:
text = f.read()
return SAK_replace(text)
def SAK_replace(s):
lines = s.splitlines()
for index, l in enumerate(lines):
if l.endswith('.txt'):
lines[index] = get_text_from_file(l)
return linesep.join(lines)
这篇关于如何加入合并拆分行并将文件中的数据替换为同一字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!