[英]Delete first two rows of a huge csv file using python
我想使用python删除具有良好性能的巨大csv文件(3GB)的标题和第一行。
import csv
import pandas as pd
def remove2rows(csv_file):
data = pd.read_csv(csv_file)
data = data.iloc[1:]
data.to_csv(csv_file, header=None, index=False)
if __name__ == "__main__":
remove2rows(filename)
此脚本有效但需要一些时间,可能是因为它读取整个文件并将从第 3 行开始到文件末尾的每一行写入一个新的 csv 文件。
有什么方法可以提高性能吗?
请注意,“从文件中删除行”的唯一方法是读取整个文件(尽管不一定一次全部 xD)并将选定的行写回新文件。 这就是文件的工作方式。
但是,在这里不使用 panda 肯定会节省时间——panda 是一种用于对表格数据进行计算的工具,而不是文件实用程序。 使用 stdlib 的 csv 模块或者更简单的只是简单的文件功能(如果你 101% 确定你的 csv 不包含嵌入的换行符)可能会更有效,至少 wrt/内存使用,并且可能 wrt/raw perfs。
问题:删除一个巨大的 csv 文件的前两行
这个例子做:
找到第二个 NewLine 的偏移量,将文件位置改为它并复制到文件末尾。
如果您获得任何改进的性能,请返回报告!
参考:
bytes.find(sub[, start[, end]])
返回数据中找到子序列 sub 的最低索引,
将文件位置更改为给定的字节偏移量。
shutil.copyfileobj(fsrc, fdst[, length])
将复制从当前文件位置到文件末尾的内容。
import io, shutil
DATA = b"""First line to be skipped
Second line to be skipped
Data Line 1
Data Line 2
Data Line 3
"""
def main():
# with open('in_filename', 'rb') as in_fh, open('out_filename', 'wb') as out_fh:
with io.BytesIO(DATA) as in_fh, io.BytesIO() as out_fh:
# Find the offset of the second NewLine
# Assuming it within the first 70 bytes
# Assuming NO embeded NewLine
# Adjust it to your needs
buffer = in_fh.read(70)
offset = 0
for n in range(2):
offset = buffer.find(b'\n', offset) + 1
print('Change the file position to: {}'.format(offset))
in_fh.seek(offset)
# Copy to the end of the file
shutil.copyfileobj(in_fh, out_fh)
# This is only for demo printing the result
print(out_fh.getvalue())
if __name__ == "__main__":
main()
输出:
Change the file position to: 59 b'Data Line 1\\nData Line 2\\nData Line 3\\n'
用 Python 测试:3.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.