2017-01-03 221 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:哦,謝謝!會看起來。 –