将大文件分割成块

ABH*_* EA 2 python yield

我有一个包含 7946479 条记录的文件,我想逐行读取该文件并插入到数据库(sqlite)中。我的第一种方法是打开文件逐行读取记录并同时插入数据库,因为它处理大量数据,需要很长时间。我想改变这种幼稚的方法,所以当我在互联网上搜索时我看到了这个 [python-csv-to-sqlite][1] ,他们在 csv 文件中有数据,但我的文件是dat格式,但我喜欢这个问题的答案,所以现在我尝试这样做在解决方案中。 /sf/ask/415968171/

他们使用的方法就像首先将整个文件分成块,然后执行数据库事务,而不是一次写入每条记录。

所以我开始编写一个代码来将我的文件分割成块这是我的代码,

file = r'files/jan.dat'
test_file = r'random_test.txt'


def chunks(file_obj, size=10000):
counter = 0
file_chunks = []
temp_chunks = []

for line in file_obj:
    if line == '\n':
        continue
    if counter != size:
        temp_chunks.append(line)
        counter += 1
    else:
        file_chunks.append(temp_chunks)
        temp_chunks = []
        counter = 0
file_obj.close()
if len(temp_chunks) != 0:
    file_chunks.append(temp_chunks)

yield file_chunks

if __name__ == '__main__':
    split_files = chunks(open(test_file))
    for chunk in split_files:
        print(len(chunk))
Run Code Online (Sandbox Code Playgroud)

输出是 795,但我想要的是将整个文件分割成大小为 10000 的块

我不知道这里出了什么问题,我无法在这里共享我的整个文件,因此为了测试可以使用此代码生成一个包含 7946479 行的文件

TEXT = 'Hello world'
FILE_LENGTH = 7946479

counter = 0
with open(r'random_test.txt', 'w') as f:
    for _ in range(FILE_LENGTH):
        f.write(f"{TEXT}\n")
Run Code Online (Sandbox Code Playgroud)

这就是我的原始文件的样子(文件格式是dat

lat lon day mon t2m rh2m    sf  ws
5   60  1   1   299.215 94.737  209.706 5.213
5   60.25   1   1   299.25  94.728  208.868 5.137
5   60.5    1   1   299.295 94.695  207.53  5.032
5   60.75   1   1   299.353 94.623  206.18  4.945
5   61  1   1   299.417 94.522  204.907 4.833
5   61.25   1   1   299.447 94.503  204.219 4.757
5   61.5    1   1   299.448 94.525  203.933 4.68
5   61.75   1   1   299.443 94.569  204.487 4.584
5   62  1   1   299.44  94.617  204.067 4.464
Run Code Online (Sandbox Code Playgroud)

Yoh*_*ace 6

对文件进行分块的一种简单方法是使用f.read(size)直到没有剩余内容。然而,此方法适用于字符数而不是行。

test_file = 'random_test.txt'


def chunks(file_name, size=10000):
    with open(file_name) as f:
        while content := f.read(size):
            yield content


if __name__ == '__main__':
    split_files = chunks(test_file)
    for chunk in split_files:
        print(len(chunk))

Run Code Online (Sandbox Code Playgroud)

对于最后一个块,它将采用剩下的内容,这里是143字符


与线相同的功能

test_file = "random_test.txt"


def chunks(file_name, size=10000):
    with open(file_name) as f:
        while content := f.readline():
            for _ in range(size - 1):
                content += f.readline()

            yield content.splitlines()


if __name__ == '__main__':
    split_files = chunks(test_file)

    for chunk in split_files:
        print(len(chunk))


Run Code Online (Sandbox Code Playgroud)

对于最后一个块,它将采取剩下的一切,这里的6479