Get name attribute of IO_Bufferedreader

Question:

What I am wanting to do is use the name of the current file I have that is from a generator and use the first section of the name + append .csv

The buffered stream looks like this

<_io.BufferedReader name='data/20160107W FM0.xml'>

I am having an issue with this code:

for file_to_read in roots:
        print(file_to_read)
        base = os.path.basename(file_to_read)
        print(base)
        name_to_write = os.path.splitext(file_to_read)[0]
        outname = str(name_to_write[0]) + ".csv"
        outdir = "output"
        with open(os.path.join(outdir, outname), 'w', newline='') as csvf:

I receive this error which I believe means I am trying to split the stream rather than the name attribute of the buffered stream. Which leads me to this error.

$ python race.py data/ -e .xml
<_io.BufferedReader name='data/20160107W FM0.xml'>
Traceback (most recent call last):
  File "race.py", line 106, in <module>
    data_attr(rootObs)
  File "race.py", line 40, in data_attr
    base = os.path.basename(file_to_read)
  File "C:UsersSaythAnaconda3libntpath.py", line 232, in basename
    return split(p)[1]
  File "C:UsersSaythAnaconda3libntpath.py", line 204, in split
    d, p = splitdrive(p)
  File "C:UsersSaythAnaconda3libntpath.py", line 139, in splitdrive
    if len(p) >= 2:
TypeError: object of type '_io.BufferedReader' has no len()

My expected output is:

20160107W FM0.csv 
Asked By: sayth

||

Answers:

for a file you are reading/writing this works:

filepath = '../data/test.txt'

with open(filepath, 'w') as file:
    print(file)  # -> <_io.TextIOWrapper name='../data/test.txt' mode='w' encoding='UTF-8'>
    print(file.name)  # -> ../data/test.txt

but the type here is <_io.TextIOWrapper name='../data/test.txt' mode='w' encoding='UTF-8'> so i am not entirely sure how you open your file or get a _io.BufferedReader.

i assume they are both derived from io.FileIO and should therefore have a .name attribute.

thanks to Ashwini Chaudhary‘s comment, i can recreate your exact situation:

from io import BufferedReader

filepath = '../data/test.txt'

with BufferedReader(open(filepath, 'r')) as file:
    print(file)  # -> <_io.BufferedReader name='../data/test.txt'>
    print(file.name)  # -> ../data/test.txt
Answered By: hiro protagonist
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.