2017-04-26 36 views
0

我是新編程的人,特別是Python。但我需要這個程序來爲研究目的工作。錯誤看起來是這樣的:Python:TypeError:強制爲Unicode:需要字符串或緩衝區,找到文件

('read db data from ==>', u'C://Users//DBF.txt', 'and input file data from ==>', u'C://Users//IF.txt') 
<open file 'C://Users//OpPanda_S_R', mode 'r' at 0x0000000006309030> 
Traceback (most recent call last): 
File "C:/Users/Test.py", line 48, in <module> 
if op.exists(f) & op.getsize(f): 
File "C:\Users\genericpath.py", line 26, in exists 
os.stat(path) 
TypeError: coercing to Unicode: need string or buffer, file found 

Process finished with exit code 1 

這是代碼的相關部分:

f = open(str(outputFileGroupName)+"_"+str(group)) 
print f 
if op.exists(f) & op.getsize(f)>0: 
    if globals()["same_market_"+str(group)+"_file"].shape[0] > 0: globals()["same_market_"+str(group)+"_file"].to_csv(outputFileGroupName, index=False,mode='a',header=False) 
     pass 
if ~contolGroupValidityCheck: 
    new_entry_occured.append(diff_market_plan_file).to_csv(globals()[str(outputFileGroupName)+"_tmp"], index=False) 

我沒有檢查這些帖子,TypeError: coercing to Unicode: need string or buffer, file found Python TypeError: coercing to Unicode: need string or buffer, file found TypeError: coercing to Unicode: need string or buffer, dict found Python writing to CSV... TypeError: coercing to Unicode: need string or buffer, file found,但我找不到合適解。

如果有人能幫助一個noob出來,我會很高興。我相信,當你看到它時,你的「專業人員」已經能夠解決問題。所以有人可以告訴我爲什麼我在第48行得到這個特定的錯誤?我可以看到,在上述目錄中文件已經創建,我只是檢查文件是否存在,如果它的長度大於0那麼據此做相應的陳述。

回答

0
f = open(str(outputFileGroupName)+"_"+str(group)) 

在這一點上,f是在文件手柄os.path.existsos.path.getsize期望一個文件名

因此,首先使用名稱檢查是否存在/大小,然後再打開它。

name = str(outputFileGroupName)+"_"+str(group) 
if op.exists(name) and op.getsize(name)>0: 
    f = open(name) 

,不使用邏輯&多個條件爲短路是行不通的,如果文件不存在,getsize仍稱,你會得到一個IOError。使用and

另外:代碼中的if ~contolGroupValidityCheck也是一樣。使用not。保留~,& ...用於按位操作,而不是邏輯操作。

+0

法布爾:謝謝你,一羣人。錯誤已解決。 – Rowen

+0

@Fabre:我可以問你多一點嗎?在這一行:'globals [「diff_market _」+ str(group)+「_ file」] = input_data [input_data [inputFileRootProfile] .isin(「diff_market _」+ str(group)+「db」[dbFileRootProfile])] m得到一個錯誤:'TypeError:字符串索引必須是整數,而不是unicode'。你能幫我嗎? – Rowen

+0

我想你是傳遞一個字符串作爲列表索引。分解你的線,看看哪一個。在你的行中有3個'[]'訪問,很難弄清楚這是怎麼回事。 –

相關問題