0

I have a function that will open a file, look for a line in the file, and attempt to replace the voltage in the line for every iteration of my voltage loop I created below the function and I print it for testing purposes.

I am getting this error:

File "test.py", line 23, in

update_code(voltage)

File "test.py", line 11, in update_code

data[i-1]='VINPUT input 0 ' + in +'\n'

TypeError: cannot concatenate 'str' and 'float' objects

# function required to change the input voltage in the pbit.sp file:

def update_code (vin):
    ff=open("pbit.sp", "r+")
    i=0
    data= ff.readlines()
    for line in data:
        i+=1
        if  'VINPUT' in line:
            data[i-1]='VINPUT input 0 ' + vin +'\n'

    ff.seek(0)
    ff.truncate()
    ff.writelines(data)
    ff.close()


prob=[]

voltages = [0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.42, 0.44, 0.46, 0.48, 0.5]
for voltage in voltages:
    update_code(voltage)
    print(voltage)

I am very new to Python, I would love support from the community!

Community
  • 1
  • 1
Jac Mills
  • 15
  • 1
  • 6
  • The error message is quite readable here. It says you can't concatenate str and float objects. – Austin Apr 20 '20 at 14:34

2 Answers2

1

You need to cast your float to a string in order to concatenate. Change

data[i-1]='VINPUT input 0 ' + vin +'\n'

to

data[i-1]='VINPUT input 0 ' + str(vin) +'\n'
Josh Clark
  • 964
  • 1
  • 9
  • 17
0

As the error message says: TypeError: cannot concatenate 'str' and 'float' objects. You've to convert float value to str before concatenating it.

Modify this line:

data[i-1] = 'VINPUT input 0 ' + vin +'\n'

to this:

data[i-1] = 'VINPUT input 0 ' + str(vin) +'\n'
Devansh Soni
  • 771
  • 5
  • 16