Hello, there is such a task: a text file of n lines is input, each line has one word

#word1 #word2 .... #wordn 

It is necessary to get a text file at the output, in each line of which there will be m words (besides, the number n can be not a multiple of m, i.e. the last line can contain words <m)

 def split(lst, size): arrs = [] while len(lst) > size: pice = lst[:size] arrs.append(pice) lst = lst[size:] arrs.append(lst) return arrs f1 = open(r'c:\hashtags.txt') lines = f1.readlines() f1.close() list20 = str(split(lines,20)) f2 = open(r'c:\20 per line.txt', 'w') f2.write(list20) f2.close() 

If I write list20 to a text file, I get only 1 line and the text of the form [['#collegestudent\n', '#pictoftheday\n', '#flexibility\n', '#instabirthday\n', '#sunrise_sunsets_aroundworld\n', '#селфипалка\n', '#bookaddict\n', '#bodybuildingmotivation\n', '#birthdaycake\n', '#heavy\n', '#naildesigns\n', '#jobs\n', '#rims\n', '#motivation\n', '#liprings\n', '#tats\n', '#iloveheels\n', '#likesreturned\n', '#clouds_of_our_world\n', '#hungry\n']

Please suggest how the output file to the desired form

 #word1 #word2 ... #word20 #word21 ......... #word40 

    2 answers 2

     def chunk_data(data, chunk_size): for i in range(0, len(data), chunk_size): yield data[i:i+chunk_size] with open(r'c:\hashtags.txt') as in_fh, open(r'c:\20 per line.txt', 'w') as out_fh: for lines in chunk_data(in_fh.readlines(), 20): out_fh.write(' '.join(i.strip() for i in lines)+ '\n') 

      A file is an iterator over lines in Python, so as not to load the entire file into memory, you can split the file into groups of m lines using the zip(*[iterator]*m) idiom shown in itertools grouper() recipe :

       from itertools import zip_longest def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) 

      Reading words from one file and grouping them in the output file:

       with open('words.txt') as file, open('output.txt', 'w') as output_file: for words in grouper(file, m, fillvalue=''): print(*map(str.strip, words), file=output_file) 

      For example, to enter:

       #word1 #word2 #word3 #word4 #... 

      and m=2 result :

       #word1 #word2 #word3 #word4 #... 

      For m = 3, the result is :

       #word1 #word2 #word3 #word4 #... 

      To understand the code can help: What does * (asterisk) and ** double star in Python mean?