简体   繁体   English

将对象写入python文件

[英]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 ? 如何缓冲输出,变量vals是什么数据类型?

vals is a list. vals是一个列表。 If you want to write a list of strings to a file, as opposed to an individual string, use writelines : 如果要将字符串列表而不是单个字符串写入文件,请使用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()

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. 首先,与其单独打开和关闭文件,不如使用可自动执行工作的语句 。关于错误,因为它说write方法仅接受字符缓冲区对象,因此您需要将列表转换为字符串。

For example you can use join function that join the items within an iterable object with a specific delimiter and return a concatenated string. 例如,您可以使用join函数,该函数使用特定的定界符将可迭代对象中的项目连接在一起,并返回一个串联字符串。

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 : 另外,作为文件对象是迭代器的一种更加Python化的方式,您可以在以下代码中进行操作,并通过调用其next方法获得第一行,并将其余的传递给join函数:

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

You cannot "write" objects to files. 您不能将对象“写入”文件。 Rather, use the pickle module: 而是使用pickle模块:

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. 您只能将字符串和字节写入文件,python的open()函数就像打开记事本一样将其打开。

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. 要回答您的第一个问题, vals是一个列表,因为[operation(i) for i in iterated_over]任何内容[operation(i) for i in iterated_over]都是列表理解,而列表理解会生成列表。 To see what the type of any object is, just use the type() function; 要查看任何对象的类型是什么,只需使用 type()函数即可; eg type([1,4,3]) 例如type([1,4,3])

Examples: https://repl.it/qKI/3 示例: 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 此处的文档: https : //docs.python.org/2/library/pickle.htmlhttps://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

The write function will only handle characters or bytes. write功能将仅处理字符或字节。 To write arbitrary objects, use python's pickle library. 要编写任意对象,请使用python的pickle库。 Write with pickle.dump() , read them back with pickle.load() . 与写pickle.dump()与读回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. 现在,您已编写了一个类似于abc.txt的文件,但已删除了每一行的第一行和第一个字符。 (You dropped those when constructing vals .) (您在构造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. 由于您选择将其命名为abc_format.txt ,因此abc_format.txt我怀疑这是您的意图,但是无论如何,这就是您编写文本行列表的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM