【问题标题】:Python:TypeError: coercing to Unicode: need string or buffer, file foundPython:TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到文件
【发布时间】:2017-09-23 14:40:22
【问题描述】:

我是编程新手,尤其是 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,但我找不到合适的解决方案。

如果有人可以帮助这里的菜鸟,我会非常高兴。我敢肯定,当您看到它时,您的“专业人士”已经遇到了问题。那么有人可以告诉我为什么我在第 48 行遇到这个特殊错误吗?我可以看到在上述目录中文件已经创建,我只是在检查文件是否存在以及它的长度是否大于 0相应地做相应的陈述。

【问题讨论】:

    标签: python-2.7


    【解决方案1】:
    f = open(str(outputFileGroupName)+"_"+str(group))
    

    此时,f 是文件的句柄os.path.existsos.path.getsize 需要一个文件名

    所以首先使用 name 检查存在/大小,然后再打开它。

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

    并且不要对多个条件使用逻辑&amp;,因为短路不起作用,如果文件不存在,getsize 仍然会被调用,你会得到一个IOError。使用and

    除此之外:代码中的 if ~contolGroupValidityCheck 也是如此。使用not。保留~, &amp; ... 用于按位运算,而不是逻辑运算。

    【讨论】:

    • @Fabre:我能再请你1个忙吗?在这一行:globals["diff_market_"+str(group)+"_file"] = input_data[input_data[inputFileRootProfile].isin("diff_market_"+str(group)+"_db"[dbFileRootProfile])] 我收到一个错误:TypeError: string indices must be integers, not unicode。你能帮我吗?
    • 我想你正在传递一个字符串作为列表索引。分解你的线路,看看是哪一条。您的行中有 3 个[] 访问,很难弄清楚这样有什么问题。
    • 会的。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2015-02-01
    相关资源
    最近更新 更多