0

I have a following code:

 matrix_file = open("abc.txt", "rU")
 matrix = matrix_file.readlines()
 keys = matrix[0]
 vals = [line[1:] for line in matrix[1:]]
 ea=open("abc_format.txt",'w')
 ea.seek(0)
 ea.write(vals)
 ea.close()

However I am getting the following error:

TypeError: expected a character buffer object

How do I buffer the output and what data type is the variable vals?

6
  • vals is a list, not a string. What output did you expect to be written? Commented May 31, 2015 at 14:34
  • instead of 'w' try 'wb' Commented May 31, 2015 at 14:37
  • 1
    Consider pickle to persist objects in file. Commented May 31, 2015 at 14:38
  • @SaraSantana: I tried wb, but it didn't work either Commented May 31, 2015 at 14:43
  • @MartijnPieters: I want to output the whole matrix minus the first row and the first column. Commented May 31, 2015 at 14:43

4 Answers 4

2

vals is a list. If you want to write a list of strings to a file, as opposed to an individual string, use writelines:

 ea=open("abc_format.txt",'w')
 ea.seek(0)
 ea.writelines(vals)
 ea.close()

Note that this will not insert newlines for you (although in your specific case your strings already end in newlines, as pointed out in the comments). If you need to add newlines you could do the following as an example:

 ea=open("abc_format.txt",'w')
 ea.seek(0)
 ea.writelines([line+'\n' for line in vals])
 ea.close()
Sign up to request clarification or add additional context in comments.

4 Comments

Since the input was read with readlines(), the newlines have not been removed and don't need to be re-added.
It worked! except now the matrix in the output file has a tab at the beginning of each line, can you tell me how can I override those tabs
If it has a tab, you put it there.
You can write lines with leading tabs stripped with ea.writelines([line.lstrip('\t') for line in vals])
0

The write function will only handle characters or bytes. To write arbitrary objects, use python's pickle library. Write with pickle.dump(), read them back with pickle.load().

But if what you're really after is writing something in the same format as your input, you'll have to write out the matrix values and newlines yourself.

for line in vals:
    ea.write(line)

ea.close()

You've now written a file that looks like abc.txt, except that the first row and first character from each line has been removed. (You dropped those when constructing vals.)

Somehow I doubt this is what you intended, since you chose to name it abc_format.txt, but anyway this is how you write out a list of lines of text.

Comments

0

You cannot "write" objects to files. Rather, use the pickle module:

matrix_file = open("abc.txt", "rU")
matrix = matrix_file.readlines()
keys = matrix[0]
vals = [line[1:] for line in matrix[1:]]
#pickling begins!
import pickle
f = open("abc_format.txt")
pickle.dump(vals, f) #call with (object, file)
f.close()

Then read it like this:

import pickle
f = open("abc_format.txt")
vals = pickle.load(f) #exactly the same list
f.close()

You can do this with any kind of object, your own or built-in. You can only write strings and bytes to files, python's open() function just opens it like opening notepad would.

To answer your first question, vals is a list, because anything in [operation(i) for i in iterated_over] is a list comprehension, and list comprehensions make lists. To see what the type of any object is, just use the type() function; e.g. type([1,4,3])

Examples: https://repl.it/qKI/3

Documentation here: https://docs.python.org/2/library/pickle.html and https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Comments

0

First of all instead of opening and closing the file separately you can use with statement that does the job automatically.and about the Error,as it says the write method only accepts character buffer object so you need to convert your list to a string.

For example you can use join function that join the items within an iterable object with a specific delimiter and return a concatenated string.

with open("abc.txt", "rU") as f,open("abc_format.txt",'w') as out:
   matrix = f.readlines()
   keys = matrix[0]
   vals = [line[1:] for line in matrix[1:]]
   out.write('\n'.join(vals))

Also as a more pythonic way as the file objects are iterators you can do it in following code and get the first line with calling its next method and pass the rest to join function :

with open("abc.txt", "rU") as f,open("abc_format.txt",'w') as out:
   matrix = next(f)
   out.write('\n'.join(f))

1 Comment

Whats the problem with my answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.