如何打印刚打印到文本文件的路径。例如:
我在D:/Workspace/Python/textfile.txt上有textfile.txt路径。有像这样的字符串
string1
i have pen
i have book
string2
i have ruler
i have bag
author : stevanus
然后将textfile.txt拆分为两个文件,在每个文本文件上打印路径。打印上面的路径并在每个文件中打印下面的作者。在D:/ Workspace / savedfile的另一个路径中。实施例
textfile1.txt中的
path : D:/Workspace/savedfile/textfile1.txt <-- print the path but textfile1.txt
string1
i have pen
i have book
author : stevanus <-- print the author
textfile2.txt中的
path : D:/Workspace/savedfile/textfile2.txt <-- print the path but textfile2.txt
string2
i have ruler
i have bag
author : stevanus <-- print the author again
这是到目前为止的代码
linenum = 1
filename = ''
with open('D:/Workspace/Python/textfile.txt', 'rt') as inf:
for line in (inf):
if 'string'in line:
filename = 'D:/Workspace/savedfile/textfile{}.txt'.format(linenum)
open(filename,'w')
linenum+=1
with open(filename, 'a') as outf:
outf.write(line)
简而言之,如何打印存储的新文件的路径,并将原始文件中的字符串打印到全新文件中。抱歉我的英文不好
答案 0 :(得分:0)
我认为itertools.chain是一种更好的分割文件的方法。
在for循环之后,变量“line”变为“author:stevanus”,然后你可以将它添加到除最后一个文件之外的每个文件中。
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 = 'textfile{}.txt'.format(idx)
with open(filename, 'a') as outf:
outf.write(line)
答案 1 :(得分:0)
你可以简单地说:
string
时都会打开一个新文件author
时,将此行添加到所有已打开的文件并关闭它们它可能看起来像:
linenum = 1
files = []
with open('D:/Workspace/Python/textfile.txt', 'rt') as inf:
for line in (inf):
if 'string'in line:
filename = 'D:/Workspace/Python/textfile{}.txt'.format(linenum)
fd = open(filename,'w')
linenum+=1
files.append(fd)
elif 'author' in line:
for fd in files:
fd.write(line)
fd.close()
break
fd.write(line)
如果文件格式错误,您应该添加一些错误处理,但它适用于正确的输入文件。