这是我之前从上一个问题得到的马丁内的代码
with open('textfile.txt', 'rt') as inf:
for linenum, line in enumerate(inf, start=1):
filename = 'string {}.txt'.format(linenum)
with open(filename, 'wt') as outf:
outf.write(line)
这将只打印一行。下一行它将创建一个新的txt文件
textfile.txt中的
string 1
this is my pen
this is my book
string 2
this is my phone
this is my ...
会分成几个像这样的文本文件
字符串1.txt
中的字符串1这是我在字母串2.txt中的笔
这是我的书3.txt
字符串4.txt
中的字符串2这是我手机中的字符串5.txt
等......
但我需要像这样的那个
string 1.txt
this is my pen
this is my book
string 2.txt
this is my phone
this is my ...
等到字符串n + 1
我想改变'亚麻布'。但我不知道..
答案 0 :(得分:1)
这是最强大的解决方法....希望有所帮助
linenum = 1
filename = ''
with open('textfile.txt', 'rt') as inf:
for line in (inf):
if 'string 'in line:
filename = 'string {}.txt'.format(linenum)
open(filename,'w')
linenum+=1
continue
with open(filename, 'a') as outf:
outf.write(line)