简体   繁体   English

如何在Python中将列表列表写入文件?

[英]How do I write a list of lists to a file in python?

The code I have is this. 我的代码是这个。 I am trying to radix sort a list of numbers into a list of lists and then write that list of lists to a file, with each individual list on a different line. 我试图将数字列表基数排序为列表列表,然后将该列表列表写入文件,每个单独的列表在不同的行上。 If I try to use f.write , it gives me a character buffer expected error. 如果尝试使用f.write ,它将给我一个字符缓冲区预期错误。

from math import log

b = open("radix.in.txt").readlines()
a = [int(i) for i in b]

f = open("radix.out.txt", "w")
def getIndex(num, base, digit_num):
    return (num // base ** digit_num) % base  

def newLists(base):
    return [ [] for i in range(base) ]  

def order(q, base, digit_num):
    placehold = newLists(base)
    for num in a:
        placehold[getIndex(num, base, digit_num)].append(num)  
    return placehold

def radixSort(a, base):
    passes = 3
    new_list = a
    for digit_num in range(passes):
    new_list = order(new_list, base, digit_num)
    list_c = [str(i) for i in new_list]
    print list_c


radixSort(a, 10)

Putting f.write(list_c) in after the print list_c gives this traceback 在打印list_c之后放置f.write(list_c)可以进行追溯

Traceback (most recent call last):
  File "C:\Users\Nolan Caldwell\Desktop\HW5.py", line 29, in <module>
    radixSort(a, 10)
  File "C:\Users\Nolan Caldwell\Desktop\HW5.py", line 26, in radixSort
    f.write(list_c)
TypeError: expected a character buffer object

list_c is a list -of- str . list_cstrlist To convert that to a single str , use str.join() : 要将其转换为单个str ,请使用str.join()

f.write('\n'.join(list_c)+'\n')

Or, if you prefer, you can write each str individually: 或者,如果愿意,可以单独编写每个str

for s in list_c:
  f.write(s+'\n')

convert it to a string and use literal_eval to get it as an array while reading 将其转换为字符串,并在读取时使用literal_eval将其作为数组获取

f=open('file.txt','w')
a=[[1,2],[3,4],[4,5]]
b=str(a)
f.write(b)

and when you read, 当你阅读时

import ast
f=open('file.txt','r')
a=f.read()
b=ast.literal_eval(a)

because the write() function can process only strings. 因为write()函数只能处理字符串。 Or convert the list of lists to a string and use write. 或将列表列表转换为字符串并使用write。

Sounds like it is a great chance to use csv module. 听起来这是使用csv模块的绝好机会。

import csv
with open('numbers.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    for lst in list_of_lists:
        writer.writerow(lst)

As others have pointed out, you need to serialize the data in some way before you can write it to a file. 正如其他人指出的那样,您需要以某种方式序列化数据,然后才能将其写入文件。 You can pickle, json encode, xml encode, stick it in a database like sqlite, write it line by line, put it in a CSV file, and etc... The "best" method (there is no best) depends on what you plan to do with that file later. 您可以进行腌制,json编码,xml编码,将其粘贴在sqlite之类的数据库中,逐行写入,将其放入CSV文件中,等等。“最佳”方法(没有最佳方法)取决于什么您打算稍后再处理该文件。 Do people need to read it? 人们需要阅读吗? Do non-python programs need to read it? 非python程序需要读取吗? Is it large enough to be concerned about the amount of space it takes? 它足够大到可以担心占用的空间吗?

If you just want to save a list of integers and want it to be readable in many programming languages, I like json 如果您只想保存一个整数列表并希望在许多编程语言中都可以读取,我喜欢json

import json
(... your other stuff here...)
new_list = order(new_list, base, digit_num)
json.dump(new_list, open('myfile.json', 'w'))

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

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