AishwaryaKulkarni
AishwaryaKulkarni

Reputation: 784

Writing an object to python file

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?

Upvotes: 0

Views: 801

Answers (4)

Eric Appelt
Eric Appelt

Reputation: 2973

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()

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

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))

Upvotes: 0

noɥʇʎԀʎzɐɹƆ
noɥʇʎԀʎzɐɹƆ

Reputation: 10647

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

Upvotes: 0

alexis
alexis

Reputation: 50200

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.

Upvotes: 0

Related Questions