Let's say I have a list with 10,000 entries. The user inputs a number, say 10. What I need to do is write all of the entries in the list to .txt files, but only 10 to each file. So the program would write the first 10, and then create a new file, and write the next 10... etc.
Thanks
count = 0
ext = 0
path = 'New/' + str(ext) + '.txt'
open(path, 'a').close()
for line in flines:
f = open(path, 'a')
if count <= x:
f.write(line)
count += 1
else:
ext += 1
path = 'New/' + str(ext) + '.txt'
count += x
f.close()
This is what I've tried, amongst some other solutions. I have a feeling that I'm missing something simple.
This is different to the other question pointed out above as that's talking about a text file and this is talking about a list.
Use a generator to split lines list like this:
>>> def splited_lines_generator(lines, n):
... for i in xrange(0, len(lines), n):
... yield lines[i: i + n]
...
>>> for index, lines in enumerate(splited_lines_generator(['a', 'b', 'c', 'd', 'e'], 2)):
... with open('new/' + str(index) + '.txt', 'w') as f:
... f.write('\n'.join(lines))
...
I have used ['a', 'b', 'c', 'd', 'e']
and 2 just as an example. After running this three files will be created, first two will contain two lines and last one will contain a single line (only e
). Note that, directory new
must be present before running this.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments