4

I'd like to read a file in text mode line-wise, but at the same time I'd like to insert an intermediate step which works on bytes data and basically counts the bytes read so far.

Is there a good way in the standard library to achieve that (without manually opening in bytes mode, searching for newlines, encoding, ...)? At the end I need a text reading object (being used in the CSV reader) which additionally has a byte counter.

3
  • You want to know how many bytes were read? Do you know the encoding of the file? Commented Sep 2, 2014 at 10:07
  • Are you just looking for the tell method of file objects?
    – roippi
    Commented Sep 2, 2014 at 10:18
  • Yes, I will specify the encoding as usual when opening the text file. The .tell() method is disabled for some reason due to buffering or so. All I need is reading the CSV while counting the number of raw bytes read.
    – Gere
    Commented Sep 2, 2014 at 10:19

1 Answer 1

3

Python 2

csv module works with binary files in Python 2 therefore you could just call file.tell() method to get the current byte offset in the file.

Python 3

You can't use text_file.tell() (TextIOBase instance) -- it is documented to return an opaque number that may not correspond to the actual byte position.

If it is acceptable for your use case to get the byte offset with ± bufsize precision then:

file = open(filename, 'rb') # open in binary mode
text_file = io.TextIOWrapper(file, newline='') # text mode
# pass text_file to csv module
byte_offset = file.tell() # get position ± buffering
2
  • Probably worth mentioning that you can disable buffering by passing 0 to open's third argument, buffering.
    – roippi
    Commented Sep 2, 2014 at 14:18
  • @roippi: TextIOWrapper is documented to work only with buffered files. Passing an unbuffered file may lead to wrong results today or in the future.
    – jfs
    Commented Sep 2, 2014 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.