2015-10-15 30 views
0

我有一个相当简单的问题。我在Python中定义了一个非常大的列表,如果我将它输出到1个文本文件,文件大小将达到200mb大。我无法轻松打开。我可以使用Python中的filterwriter设置最大文件大小吗?

我想知道Python中是否有任何可用的选项可以设置特定写入文件的最大大小,并且如果超过大小可以创建一个新文件?

总结:

  • 现状:1个文件(200MB)
  • 理想状况:8个文件(每个25MB)

到目前为止的代码:

file = open("output_users.txt", "w") 
file.write("Total number of users: " + str(len(user_id))) 
file.write(str(user_id)) 
file.close() 
+0

你会在文件上手动做什么?编辑,阅读?如果你自己不需要这样做,你可以使用压缩格式。 – wap26

+0

我只需要阅读它!一旦创建,我不需要再编辑了! @ wap26 – Rotan075

回答

1

open()中没有内置的方法。我建议你将数据分成几个块,然后每个块打开一个不同的文件。例如,假设你有超过一万个项目(为简单起见,我在这里使用整数,但它们可能是用户记录或你正在处理的任何项目)进行处理。你可以它们分割成十个大块像这样,使用itertools模块的groupby功能,让您的工作更容易一点:

import itertools 
original_data = range(10003) # Note how this is *not* divisible by 10 
num_chunks = 10 
length_of_one_chunk = len(original_data) // num_chunks 
chunked_data = [] 
def keyfunc(t): 
    # Given a tuple of (index, data_item), return the index 
    # divided by N where N is the length of one chunk. This 
    # will produce the value 0 for the first N items, then 1 
    # for the next N items, and so on, making this very 
    # suitable for passing into itertools.groupby. 
    # Note the // operator, which means integer division 
    return (t[0] // length_of_one_chunk) 

for n, chunk in itertools.groupby(enumerate(original_data), keyfunc): 
    chunked_data.append(list(chunk)) 

这将产生一个chunked_data名单与11的长度;每个元素都是数据项列表(在这种情况下,它们只是整数)。 chunked_data的前十项将全部具有N个项目,其中N是length_of_one_chunk(在这种情况下恰好为1000)的值。 chunked_data的最后一个元素将是3个剩余项目的列表,这些项目并不适用于其他列表;您可以将它们写入单独的文件,或者将它们追加到最后一个文件的末尾。

如果将range(10003)更改为range(10027),则N将为1002,最后一个元素将包含7个剩余项目。等等。

然后你只需运行chunked_data通过一个for循环,并为它里面每个列表,处理数据正常,每次打开一个新的文件。你会得到你的10个文件(或8个,或者任何你设置的num_chunks)。

+0

谢谢!这会帮助我很多!感谢您的回答和明确的解释。 – Rotan075

相关问题