Reputation: 1447
I have a simple method for which I have to do the following:
Therefore I made the following:
import pandas as pd
import os
path = '/test'
os.chdir(path)
def writeScores(test):
with open('output.txt', 'w') as f:
var = "\n", test, "\n"
f.write(var)
This however gives me the following error. Any thoughts where I go wrong?
TypeError: expected a character buffer object
Upvotes: 2
Views: 65
Reputation: 12728
You have this error because your first argument is not string, you should pass it a string ,you can use this simple script and also you can change "rw" to "w+" or use 'a+' for appending (not erasing existing content)
import os
writepath = 'some/path/to/file.txt'
mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
f.write('Freeman Was Here!\n')
Upvotes: 2
Reputation: 6762
Instead of string you have created a tuple here with comma separated values like
var = "\n" + test + "\n"
So you can't write that tuple directly on the file.so lets put values inside that tuple to a string as:
with open('output.txt', 'w') as fp:
var = "\n", test, "\n"
fp.write(''.join('%s' % x for x in var))
and the much better way is answered by @Jean-François Fabre
Upvotes: 0
Reputation: 3719
I assume you want to concatinate the string, so use +
instead of ,
import pandas as pd
import os
#path = '/test'
#os.chdir(path)
def writeScores(test):
with open('output.txt', 'w') as f:
var = "\n" + test + "\n"
f.write(var)
writeScores("asd")
Upvotes: 0
Reputation: 140168
you're trying to write a tuple
to your file.
While it would work for print
since print
knows how to print several arguments, write
is more strict.
Just format your var
properly.
var = "\n{}\n".format(test)
Upvotes: 2