Unexpected result when trying to open CSV file with Python3 using VS Code

Viewed 147

I'm trying to open a csv file using Python (Python 3.9.0, in VS Code, MacOS), using with open. The basic code I have is as follows:

import csv
import os

file_to_load = os.path.join("resources","original_file.csv")
with open(file_to_load) as starting_numbers:
    print(starting_numbers)

The result I got was:

<_io.TextIOWrapper name='resources/original_file.csv' mode='r' encoding='UTF-8'>

The result I expected was:

<open file 'Resources/original_file.csv', mode 'r' at 0x[memory address]>

I came across this question from four years ago, but it doesn't seem to be directly related to my problem. I'm not currently trying to get a full readout of the file, just the memory allocation.

1 Answers

<open file ...> was the python 2 string representation of an open file. In python 3, file management was decomposed into layers to implement different bits of functionality. A text wrapper will decode the file's bytes into python 3's strings which are fully unicode enabled, while a binary file just needs a reader. See open and Text I/O.

>>> open('test.py')
<_io.TextIOWrapper name='a.py' mode='r' encoding='UTF-8'>
>>> open('test.py', 'rb')
<_io.BufferedReader name='a.py'>

When opening a file in text mode, TextIOWrapper is layered on the binary BufferedReader

>>> f = open('test.py')
>>> f.buffer
<_io.BufferedReader name='test.py'>

Old examples written for python 2 don't necessarily mention that they are python 2 and you may need to "read the tea leaves" to figure it out. A file object looking like <open file ...> is a dead giveaway.

Related