gpt4 book ai didi

python - 使用python从csv文件中提取部分数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:17 25 4
gpt4 key购买 nike

问题

从文件中提取数据 block 。

描述

Python 读取文件。如果它找到特定的字符串,它就会开始将所有下一行复制到输出文件中(包括第一行),直到“关闭”。 key 字符串仅位于第一行。

尝试

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

关于python - 使用python从csv文件中提取部分数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56174378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com