0

I have a text file which has the following data,

This is the pattern i have in my input file

1111
2222
3333
4444
5555
6666
7777
8888
9999

i want the output file to have the following:

1111222233334444
5555666677778888
9999

That is, i am trying to merge the 4 line into a single line and write it to my output file.

I have written the below code, but somwhow it is not doing the job.Can anybody help me?

def open_file(filename):
    try:
        mod_list= []
        values = []
        for line in file(filename):

            line = line.rstrip()
            mod_list.append(line)

        i = iter(values)        
        for t in zip(*repeat(i, 4)):
            print(''.join(t))
            new_file.write(''.join(t)) 

        new_file.close() 
        file(filename).close()

    except Exception,e:
        print str(e)
        exit(1)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
k11
  • 167
  • 1
  • 3
  • 16
  • 4 line or 4 numbers? – Zabir Al Nazi Apr 21 '20 at 10:00
  • Are 1111, 2222, etc on separate lines in the input file, or is everything one line separated by spaces? How about the output? – pallgeuer Apr 21 '20 at 10:03
  • What were the results of your debugging attempts? At what point exactly does the code do something you do not understand? – mkrieger1 Apr 21 '20 at 10:05
  • yes, 1111 ,2222 on seperate lines.. – k11 Apr 21 '20 at 10:05
  • for t in zip(*repeat(i, 4)) seem to not combine the 4 lines into 1 for me – k11 Apr 21 '20 at 10:07
  • 1
    Then break it up in smaller parts. Apparently you do not understand how `zip`, `repeat` and `*args` work together. Maybe you could ask a more specific question about one of them. – mkrieger1 Apr 21 '20 at 10:09
  • @dipk11 try https://stackoverflow.com/a/61341007/13062813 – Joshua Varghese Apr 21 '20 at 11:24
  • I find this simple approach keeping your input string in the file "txt.txt" Try this: f= open('txt.txt','r') i=1 concat="" concat1="" mylist = []; for line in f: concat=concat+line.rstrip() if(i%4 == 0): mylist.append(concat) concat = "" concat1 = "" else: concat1 = concat1+line.rstrip() i=i+1 print(mylist[0:]) print("Remaining lines:",concat1) a second print will just print the remaining lines. It works!! – LOKENDRA Apr 21 '20 at 11:31

3 Answers3

-1

If they are multiple lines,

file.txt

11
22
1233
34234

Just take 4 chunks at a time and add it to a final list, finally write those strings with writelines().

a = open('file.txt', 'r').readlines()

final = []
buf = []
for line in a:
   if len(line.strip()) != 0:
       buf.append(line.strip())
   if len(buf) == 4:
       final.append(''.join(a for a in buf) + '\n')
       buf.clear()

outF = open("myOutFile.txt", "w")
outF.writelines(final)
outF.close()

Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60
  • better use %4 instead of ==4 in the if condition , to match it to n number of lines.. see this:I find this simple approach keeping your input string in the file "txt.txt" Try this: f= open('txt.txt','r') i=1 concat="" concat1="" mylist = []; for line in f: concat=concat+line.rstrip() if(i%4 == 0): mylist.append(concat) concat = "" concat1 = "" else: concat1 = concat1+line.rstrip() i=i+1 print(mylist[0:]) print("Remaining lines:",concat1) – LOKENDRA Apr 21 '20 at 11:32
  • 2
    What do you mean?? I cleared the array. Why do I need to check %4? – Zabir Al Nazi Apr 21 '20 at 11:34
  • aggreed !! I missed that "len" !! – LOKENDRA Apr 21 '20 at 11:39
-1

Now lets optimize this for larger files:

with open(input_file) as f, open(output_file,'w') as res:
    while True:
        out = ''
        for j in range(4):
            out+=f.readline().strip()
        if out == '':
            break
        out+='\n'
        res.write(out)

Let:

l = open(filename,'r').splitlines()
>>>l
[1111, 2222, 3333 ,4444, 5555, 6666, 7777, 8888 ,9999]

Now we will create the pairs:

l = [l[i:i+4] for i in range(0,len(l),4)]
>>> l
[[1111, 2222, 3333, 4444], [5555, 6666, 7777, 8888], [9999]]
Now we will create the line for the output text:
out = '\n'.join(''.join(str(j) for j in i) for i in l)
>>> out
1111222233334444
5555666677778888
9999

Now write out to the output file:

f = open(output_file,'w')
f.write(out)
f.close()
tripleee
  • 175,061
  • 34
  • 275
  • 318
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
-1

Check this solution. Make sure to remove the new line character before writing the content into the output file and write a new line when needed.

max_line = 4
count=0

with open('output_file_name', 'a') as out_file, open('input_file_name','r') as in_file:
    for line in in_file:
        out_file.write(line.strip('\n'))
        count += 1
        if count == 4:
            out_file.write('\n')
            count=0
    out_file.write('\n')
Sathish
  • 44
  • 3