首页 > 解决方案 > Python2.7 TypeError: coercing to Unicode: need string or buffer, NoneType found

问题描述

我正在尝试运行以下代码,但在标题中出现错误,我看到第 12 行有问题,但我对 Python 不是很熟练,关于这一行的问题有什么提示吗?

import binascii
import argparse
import sys
parser = argparse.ArgumentParser(description='Convert .bin files to CSV and clipboard')

parser.add_argument("-i", "--inputfile", action="store")
parser.add_argument("-s", "--save", action="store_true")
parser.add_argument("-o", "--outputfile", action="store")

args = parser.parse_args()

with open(args.inputfile, 'rb') as f:
    content = f.read()
string = binascii.hexlify(content)
#print string
length = len (string)
length = length - 2

i = 0
k = 0

while k < length:
    string = string[:(2+i*3)] + "," + string[(2+i*3):]
    i = i + 1
    k = i * 2   

# Add write command for DIAG-Port connection
string = "ew 0 1 0 \"" + string + "\""

# print complete content
print string

if args.save:
    with open(args.outputfile, "w") as text_file:
        text_file.write(string)

# Copy content to clipboard
try:
    from Tkinter import Tk
except ImportError:
    # welcome to Python3
    from tkinter import Tk
    raw_input = input

r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(string)

错误:

    Traceback (most recent call last):
  File "trans_cp.py", line 12, in <module>
    with open(args.inputfile, 'rb') as f:
TypeError: coercing to Unicode: need string or buffer, NoneType found

标签: python

解决方案


错误很明显,args.inputfileNone(因为您没有使用--inputfileor-i参数调用脚本)。尝试使用提供的文件的路径进行调用。

您还可以将此参数设置为位置或添加required=True以避免将来出现此问题。


推荐阅读