1

I have test.txt file:

"hi there 1, 3, 4, 5"

When I use python to read it,how can I read it part by part for example first I read the first 4 character and then read the next 4 and then all of the left.

my code here:

with open(file, 'r', encoding='utf-8', errors='ignore') as f:
             lines = f.read(4)

Use this code I can only read the first 4 character,any idea that I can ready each 4 characters in a loop until read all of them?

martineau
  • 119,623
  • 25
  • 170
  • 301
William
  • 3,724
  • 9
  • 43
  • 76

3 Answers3

3

You can use the two-argument form of iter, which takes a callable and a sentinel value. It will call the callable repeatedly until it receives the sentinel value.

>>> from functools import partial
>>> with open('test.txt') as f:
...     for chunk in iter(partial(f.read, 4), ''):
...         print(repr(chunk), len(chunk))
...
'"hi ' 4
'ther' 4
'e 1,' 4
' 3, ' 4
'4, 5' 4
'"\n\n' 3
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

Does this answer your question?

with open('z.txt', 'r', encoding='utf-8', errors='ignore') as f:
    lines = f.read()
    x=len(lines)//4
    print(x)
    with open('z.txt', 'r', encoding='utf-8', errors='ignore') as c:
        for times in range(x+1):
            l=c.read(4)
            print(l)

Output:

5
"hi
ther
e 1,
 3,
4, 5
"
0

Using while loop

  with open(file, 'r', encoding='utf-8', errors='ignore') as f:
                 lines = f.read()
                 total_length = len(lines)
                 var = 4
                 print(lines)
                 while var <= total_length :
                     print(lines[(var-4):var])
                     var += 4
                 else:
                     print(lines[(var-4):var])
Rima
  • 1,447
  • 1
  • 6
  • 12