获取IO_Bufferedreader

时间:2017-01-03 12:30:01

标签: python python-3.x

我想要做的是使用来自生成器的当前文件的名称并使用名称的第一部分+ append .csv

缓冲流看起来像这样

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

我遇到此代码的问题:

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:

我收到此错误,我认为这意味着我正在尝试拆分流而不是缓冲流的name属性。这导致我犯了这个错误。

$ 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:\Users\Sayth\Anaconda3\lib\ntpath.py", line 232, in basename
    return split(p)[1]
  File "C:\Users\Sayth\Anaconda3\lib\ntpath.py", line 204, in split
    d, p = splitdrive(p)
  File "C:\Users\Sayth\Anaconda3\lib\ntpath.py", line 139, in splitdrive
    if len(p) >= 2:
TypeError: object of type '_io.BufferedReader' has no len()

我的预期输出是:

20160107W FM0.csv 

1 个答案:

答案 0 :(得分:3)

对于一个文件你读/写这个有效:

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

type此处为<_io.TextIOWrapper name='../data/test.txt' mode='w' encoding='UTF-8'>,因此我不完全确定您如何打开文件或获取_io.BufferedReader

我认为它们都来自io.FileIO,因此应该具有.name属性。

感谢 Ashwini Chaudhary 的评论,我可以重新创建您的具体情况:

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