我在python中还是新手。我在这里需要一些关于逻辑的帮助..
到目前为止这是代码..
from itertools import chain
filename = 'D:/Workspace/Python/textfile.txt'
with open(filename, 'rb') as inf:
header = next(inf)
for index, line in enumerate(inf,start=1):
with open('D:/Workspace/Python/textfile{}.txt'.format(index) ,'w') as outf:
outf.write('Path : %s\n' %outf.name)
outf.write(header)
for line in chain([line], inf):
if 'string' in line:
header = line
break
outf.write(line)
for idx in range(1, index):
filename = 'D:/Workspace/Python/textfile{}.txt'.format(idx)
with open(filename, 'a') as outf:
outf.write(line)
我在D:/Workspace/Python/textfile.txt上有textfile.txt路径。有像这样的字符串
date : day - month - year
string1
i have pen
i have book
string2
i have ruler
i have bag
string3
....
this is the list of item i have in string
author : stevanus
然后打印到..
textfile1.txt中的
path : D:/Workspace/savedfile/textfile1.txt
date : day - month - year <-- print this
string1
i have pen
i have book
this is the list of item i have in string1 <--print this but in string1
author : stevanus
textfile2.txt中的
path : D:/Workspace/savedfile/textfile2.txt
date : day - month - year <-- print this again
string2
i have ruler
i have bag
this is the list of item i have in string2 <-- and print this again but in string2
author : stevanus
等等其他字符串..
抱歉我的英语不好。希望它清楚
答案 0 :(得分:2)
不要试图立刻实现整个事情。相反,在编码之前,请稍微构建一下您的要求和想法。
您似乎拥有自定义格式的文件。让我们首先制定这种格式的规则:
您是否注意到了这些问题?首先解决这些问题。
现在您似乎想要生成新文件,源文件中每个部分一个。每个文件都应包含源文件的页眉和页脚,而部分标识符将插入页脚。
我建议你先尝试编写一个函数来读取源文件,识别标题,部分和页脚:
header, sections, footer = read_source_file(file_path)
如果有了这个,输出文件的代码将非常简单。当sections
是对(identifier, content)
对的列表时,代码可能如下所示:
for identifier, content in sections:
with open(...) as file:
# Write header...
# Write content lines...
# Write footer, replacing "string" with identifier
在开发read_source_file
时,您可以在交互式提示中尝试并调试您的函数,直到它完成您想要的操作。