当你在一个
with context
with
当你离开这个街区时,会自动为你关门。所以你不需要
file.close()
任何地方。
readlines
它输出一个生成器,该生成器一次从打开的文件中读取一行。这比
read()
后面跟着
split()
. 想想看。你在内存中加载一个大文件,然后要求CPU通过
\n
性格。效率不高。
opfile.write(op)
. 这是哪里
op
定义?你不想把内容写进
holding
你定义的?
with open('test.data', 'r') as myfile:
counter = 1
content = ""
start = True
for line in myfile.readlines():
if line == "-\n" and not start:
with open(str(counter) + '.md', 'w') as opfile:
opfile.write(content)
content = ""
counter += 1
else:
if not start:
content += line
start = False
# write the last file if test-file.yml doesn't end with a dash
if content != "":
with open(str(counter) + '.md', 'w') as opfile:
opfile.write(content)