2017-01-03 222 views
-2

我所想要做的就是使用当前文件的名字我是从一个发电机和使用名称的首节+追加的.csv获取IO_Bufferedreader的name属性

的缓冲流的样子这

<_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 
+2

好吧然后访问它的'name'属性:'os.path.basename(file_to_read.name)' –

+0

谢谢正在阅读文档,但看不到如何做到这一点的参考例子 – sayth

+0

检查https://docs.python.org/3/library/io.html#io.FileIO.name –

回答

2

一个文件你的readInt /写这篇作品:

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属性。

感谢阿什维尼·乔杜里的评论,我可以重新创建你的确切情况:

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 
+1

'file.buffer'或'io.BufferedReader(文件)'会给你'_io.BufferedReader'。 –

+0

@AshwiniChaudhary:哦,谢谢!会看起来。 –