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

后端 未结 2 573
-上瘾入骨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:44

    Open the file using open(), then use the file.read(x) method to read (approximately) the next x bytes from the file. You could keep requesting blocks of 4096 characters until you hit end-of-file.

    You will have to implement the splitting yourself - you can take inspiration from the csv module, but I don't believe you can use it directly because it wasn't designed to deal with extremely long lines.

提交回复
热议问题