[英]How to print path of the textfile that we just write in another directory and print string in every file in Python
如何打印僅打印到文本文件的路徑。 例:
我在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)
簡而言之,如何打印存儲的新文件的路徑以及如何將字符串從原始文件打印到所有新文件。 對不起,我的英語不好
我認為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)
您可以簡單地:
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)
如果文件格式錯誤,則應添加一些錯誤處理,但它適用於正確的輸入文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.