这里是新手。最终任务是学习如何获取两个大 yaml 文件并将它们拆分为数百个小文件。我还没有弄清楚如何使用 ID # 作为文件名,所以一次只做一件事。
第一:将大文件分割成许多。这是我的测试数据文件 test-file.yml 的一小部分。每个帖子都有一个单独的行分隔符:
-
ID: 627
more_post_meta_data_and_content
-
ID: 628
这是我的代码不起作用。到目前为止我不明白为什么:
with open('test-file.yml', 'r') as myfile:
start = 0
cntr = 1
holding = ''
for i in myfile.read().split('\n'):
if (i == '-\n'):
if start==1:
with open(str(cntr) + '.md','w') as opfile:
opfile.write(op)
opfile.close()
holding=''
cntr += 1
else:
start=1
else:
if holding =='':
holding = i
else:
holding = holding + '\n' + i
myfile.close()
欢迎所有提示、建议、指点。谢谢。
最佳答案
如果输入文件很大,将整个文件读入内存然后分割内存区域的效率非常低。试试这个:
with open('test-file.yml', 'r') as myfile:
opfile = None
cntr = 1
for line in myfile:
if line == '-\n':
if opfile is not None:
opfile.close()
opfile = open('{0}.md'.format(cntr),'w')
cntr += 1
opfile.write(line)
opfile.close()
另请注意,您不会关闭
在with
上下文管理器中打开的内容;上下文管理器的真正目的就是为您处理这个问题。
关于python3通过分隔符将大文件分割成小文件(不是大小,行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55074718/