Alex James
Alex James

Reputation: 11

Python2.7 TypeError: coercing to Unicode: need string or buffer, NoneType found

I am trying to run the following code but am getting the error in the title, I see that there is an issue with line 12 but I am not very skilled with Python, any tips on what the problem is with this line?

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)

Error:

    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

Upvotes: 1

Views: 134

Answers (1)

Cireo
Cireo

Reputation: 4427

The error is pretty clear, args.inputfile is None (because you didn't call your script with a --inputfile or -i argument). Try calling with a path to a file provided.

You can also make this argument positional or add required=True to avoid this issue in the future.

Upvotes: 1

Related Questions