问题
从文件中提取数据块。
描述
Python读取文件。如果找到特定的字符串,它将开始将所有接下来的行复制到输出文件(包括第一行),直到“关闭”为止。关键字字符串仅在第一行。
尝试
with open ('messy.csv', 'rt') as filein, open('nice.csv', 'w') as fileout:
for line in filein:
if 'string' in line:
start=0
while start<20:
fileout.write(line)
start+=1
当然,此代码的问题是复制的行没有实现(它只是重复第一行)。您能帮我解决吗?(实际上并不需要完整的解决方案)
这对您有用吗?
with open ('messy.csv', 'rt') as filein, open('nice.csv', 'w') as fileout:
copy_flag = False
start=0
for line in filein:
if 'string' in line:
copy_flag = True
if copy_flag and start < 20:
fileout.write(line)
start+=1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句