Is there a way to read a file in a loop in python using a separator other than newline

后端 未结 2 510
-上瘾入骨i
-上瘾入骨i 2021-02-14 05:49

I usually read files like this in Python:

f = open(\'filename.txt\', \'r\')
for x in f:
    doStuff(x)
f.close()

However, this splits the file

2条回答
  •  长发绾君心
    2021-02-14 06:33

    The following function is a fairly straightforward way to do what you want:

    def file_split(f, delim=',', bufsize=1024):
        prev = ''
        while True:
            s = f.read(bufsize)
            if not s:
                break
            split = s.split(delim)
            if len(split) > 1:
                yield prev + split[0]
                prev = split[-1]
                for x in split[1:-1]:
                    yield x
            else:
                prev += s
        if prev:
            yield prev
    

    You would use it like this:

    for item in file_split(open('filename.txt')):
        doStuff(item)
    

    This should be faster than the solution that EMS linked, and will save a lot of memory over reading the entire file at once for large files.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题