James Hood
James Hood

Reputation: 43

TypeError: expected a character buffer object ITS SO ANNOYING

This is what it says on the interpreter...

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    nth_term_rule(list_a)
  File "C:\Users\Jimmy\Desktop\Python 2.7 Functions Pack 1\nth_term_rule.py", line 5, in nth_term_rule
    f.write(n)
TypeError: expected a character buffer object

This is really bugging me, I'm currently in the middle of the nth term rule function for my function pack and I'm attempting to make sure the sequence is steady - if not the nth term rule would be wrong. So I'm trying to append a text file that will have every number in the list in it. Then the interpreter will go through each number, making sure the difference between it and the next one is the same as difference as the previous numbers.

Unfortunately it comes up with the error above and I don't know why.

Here is my code if it helps...

def nth_term_rule(a):
  for n in a:
    str(n)
    f = open("C:\Users\Jimmy\Desktop\Python 2.7 Functions Pack 1\Numbers.txt","a")
    f.write(n)
    f.close()
  if a[0] - a[1] == a[len(a)-2] - a[len(a)-1]: 
    b=a[1] - a[0]
    c=a[0] - b
    return (b,'n + ',c)
  else:
    return ("Error.")

Any help would be much appreciated.

Upvotes: 0

Views: 76

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122332

You are ignoring the return value of str():

str(n)

str() returns the new string, you want to assign this back to n:

n = str(n)

You probably want to avoid re-opening the file each loop iteration; just open it once:

filename = r"C:\Users\Jimmy\Desktop\Python 2.7 Functions Pack 1\Numbers.txt"
with open(filename, "a") as f:
    for n in a:
        f.write(str(n) + \n)

This adds a few more things:

  • Using the file as a context manager (with the with statement) makes sure that it is closed again automatically, when the block ends.
  • Using a raw string literal (r'...') prevents \ being interpreted as an escape sequence. That way filenames that start with a t or n or r, etc. are not interpreted as special. See string literals for more info.
  • I assumed you probably wanted to have newlines between your values when written to the file.

Upvotes: 1

Related Questions