Python:在文件中寻找EOL不起作用

2024-04-16 23:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个方法:

def get_chunksize(path):
    """
    Breaks a file into chunks and yields the chunk sizes.
    Number of chunks equals the number of available cores.
    Ensures that each chunk ends at an EOL.
    """
    size = os.path.getsize(path)
    cores = mp.cpu_count()
    chunksize = size/cores # gives truncated integer

    f = open(path)
    while 1:
        start = f.tell()
        f.seek(chunksize, 1) # Go to the next chunk
        s = f.readline() # Ensure the chunk ends at the end of a line
        yield start, f.tell()-start
        if not s:
            break

它应该将一个文件分成块,并返回块的开头(以字节为单位)和块大小。你知道吗

关键的是,一个块的结尾应该与一行的结尾相对应(这就是f.readline()行为存在的原因),但是我发现我的块根本不寻求一个EOL。你知道吗

该方法的目的是读取可以传递给csv.reader实例(通过StringIO)进行进一步处理的块。你知道吗

我一直无法发现任何明显的错误与功能…有什么想法,为什么它不移动到下线?你知道吗

我想出了一个相当笨拙的选择:

def line_chunker(path):
    size = os.path.getsize(path)
    cores = mp.cpu_count()
    chunksize = size/cores # gives truncated integer

    f = open(path)

    while True:
        part = f.readlines(chunksize)
        yield csv.reader(StringIO("".join(part)))
        if not part:
            break

这将把文件分成块,每个块都有一个csv读取器,但是最后一个块总是空的(?)而要把一系列串串在一起是相当笨拙的。你知道吗


Tags: ofcsvthepath方法sizedefcores
1条回答
网友
1楼 · 发布于 2024-04-16 23:18:55
if not s:
        break

与其查看s以查看是否在文件末尾,不如使用以下命令查看是否已到达文件末尾:

if size == f.tell(): break

这应该能解决问题。不过,我不希望CSV文件每行有一条记录。我处理过几个CSV文件,这些文件的字符串有新行:

first,last,message
sue,ee,hello
bob,builder,"hello,
this is some text
that I entered"
jim,bob,I'm not so creative...

注意,第二条记录(bob)跨越3行。csv.reader文件我能处理的。一个想法是做一些密集的cpu工作。我会创建一个线程数组,每个线程都有一个n条记录的缓冲区。拥有csv.reader文件使用循环法将记录传递给每个线程,如果缓冲区已满,则跳过该线程。
希望这有助于-享受。你知道吗

相关问题 更多 >