我是编程特别是Python的新手。但我需要这个程序用于研究目的。错误如下所示:
('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,但我无法找到合适的解决方案。
如果有人可以帮助这里的菜鸟,我会很高兴。我确定你&#34;专业人士&#34;你只是看看它就已经解决了问题。那么有人可以告诉我为什么我在第48行得到这个特殊错误?我可以看到在所述目录中创建了文件,我只是检查文件是否存在以及文件的长度是否为大于0然后相应地做各自的陈述。
答案 0 :(得分:1)
f = open(str(outputFileGroupName)+"_"+str(group))
此时,f
是文件上的句柄。 os.path.exists
和os.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
。保留~
,&
...用于按位操作,而不是逻辑操作。