如何从csv中删除前N行或后N行[已关闭]

4szc88ey  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(108)

**已关闭。**此问题需要debugging details。它目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
4天前关闭。
Improve this question
我曾经从外部系统获取CSV,数据用分号分隔,但现在它还包含前10行/行和最后2行/行的一些元数据。
请问有人可以帮助我了解如何使用python/pyspark删除它们吗?
例如:csv结构
enter image description here
请提供一些建议。谢谢你,谢谢

exdqitrt

exdqitrt1#

在“r+”模式下打开文件(因为你要重写它)。将所有行读入列表。查找BOF并使用输入列表的一个切片调用writelines()。不要忘记调用truncate()

FILENAME = 'foo.csv'

with open(FILENAME, 'r+') as data:
    lines = data.readlines()
    data.seek(0)
    data.writelines(lines[10:-2])
    data.truncate()

相关问题