Python Forum
Merge 2 lines with delimiter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Merge 2 lines with delimiter
#1
So I have code that prints out a into a file like this:
Quote:xxx.xxx.xx.xx
yyyy
#5 blank line gap
xxx.xxx.xx.xx
yyyy
#5 blank line gap
#This repeats for a while

I need to merge the 'x' and 'y' with a ':' delimiter

So end file will look like:
Quote:xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy
#etc.
Reply
#2
What have you tried?
Reply
#3
>>> text = '''xxx.xxx.xx.xx
... yyyy
...
...
...
...
...
... xxx.xxx.xx.xx
... yyyy
...
...
...
...
...
... xxx.xxx.xx.xx
... yyyy'''
>>> lines = text.split('\n')
>>> lines
['xxx.xxx.xx.xx', 'yyyy', '', '', '', '', '', 'xxx.xxx.xx.xx', 'yyyy', '', '', '', '', '', 'xxx.xxx.xx.xx', 'yyyy']
>>> lines = [line for line in lines if line] # remove blanks
>>> lines
['xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy']
>>> pairs = [(lines[i-1], lines[i]) for i in range(1, len(lines), 2)]
>>> pairs
[('xxx.xxx.xx.xx', 'yyyy'), ('xxx.xxx.xx.xx', 'yyyy'), ('xxx.xxx.xx.xx', 'yyyy')]
>>> '\n'.join(':'.join(pair) for pair in pairs)
'xxx.xxx.xx.xx:yyyy\nxxx.xxx.xx.xx:yyyy\nxxx.xxx.xx.xx:yyyy'
>>> print('\n'.join(':'.join(pair) for pair in pairs))
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy
Reply
#4
(May-03-2019, 08:28 PM)nilamo Wrote:
>>> text = '''xxx.xxx.xx.xx
... yyyy
...
...
...
...
...
... xxx.xxx.xx.xx
... yyyy
...
...
...
...
...
... xxx.xxx.xx.xx
... yyyy'''
>>> lines = text.split('\n')
>>> lines
['xxx.xxx.xx.xx', 'yyyy', '', '', '', '', '', 'xxx.xxx.xx.xx', 'yyyy', '', '', '', '', '', 'xxx.xxx.xx.xx', 'yyyy']
>>> lines = [line for line in lines if line] # remove blanks
>>> lines
['xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy']
>>> pairs = [(lines[i-1], lines[i]) for i in range(1, len(lines), 2)]
>>> pairs
[('xxx.xxx.xx.xx', 'yyyy'), ('xxx.xxx.xx.xx', 'yyyy'), ('xxx.xxx.xx.xx', 'yyyy')]
>>> '\n'.join(':'.join(pair) for pair in pairs)
'xxx.xxx.xx.xx:yyyy\nxxx.xxx.xx.xx:yyyy\nxxx.xxx.xx.xx:yyyy'
>>> print('\n'.join(':'.join(pair) for pair in pairs))
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy

This looks very good, but I is from a text file which includes the text.
otherwise I could just do
Quote:x = "xxx.xxx.xx.xx"
y = "yyyy"
print (x + ":" + y)
print ("\n")


Or am I wrong?
Reply
#5
(May-03-2019, 08:56 PM)Buddhism Wrote: Or am I wrong?
It will not work like this when reading from a file,x and y variables will just be overwritten when read each line from file.
Therefor is it easiest to first make a list as @nilmao dos,then make changes on list.
Here an other approach.
def line_concat(lst):
    temp = zip(lst[::2], lst[::-2])
    return [':'.join(i) for i in temp]

with open('xy.txt') as f:
    lst = [line.strip() for line in f if not line.isspace()]
Test.
>>> lst
['xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy']

>>> line_concat(lst)
['xxx.xxx.xx.xx:yyyy', 'xxx.xxx.xx.xx:yyyy']
>>> for line in line_concat(lst):
...     print(line)
...     
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy
Reply
#6
(May-04-2019, 12:23 AM)snippsat Wrote:
(May-03-2019, 08:56 PM)Buddhism Wrote: Or am I wrong?
It will not work like this when reading from a file,x and y variables will just be overwritten when read each line from file.
Therefor is it easiest to first make a list as @nilmao dos,then make changes on list.
Here an other approach.
def line_concat(lst):
    temp = zip(lst[::2], lst[::-2])
    return [':'.join(i) for i in temp]

with open('xy.txt') as f:
    lst = [line.strip() for line in f if not line.isspace()]
Test.
>>> lst
['xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy']

>>> line_concat(lst)
['xxx.xxx.xx.xx:yyyy', 'xxx.xxx.xx.xx:yyyy']
>>> for line in line_concat(lst):
...     print(line)
...     
xxx.xxx.xx.xx:yyyy
xxx.xxx.xx.xx:yyyy

Am I doing something wrong?
[Image: IGFJ11i.png]
You are seeing the last of the code. Those last lines are whats running. Everything else is def
The file that the program is working with the whole time is ScrapedProxys.txt

KEEP IN MIND: list_concat(lst) is above this image to run the def
But this is the error

[Image: MMTJ1Oi.png]
Reply
#7
Try to use code tags and not images with code,look at BBCode.
In my example i am running the last part in interactive shell has >>>.
Now you have put all in one function and that will not work as i have written it.
Here a example running as a script,see that need print() when running as a script.
def line_concat(lst):
    temp = zip(lst[::2], lst[::-2])
    return [':'.join(i) for i in temp]

def file_read(file_in):
    with open(file_in) as f:
        lst = [line.strip() for line in f if not line.isspace()]
        return lst

if __name__ == '__main__':
    file_in = 'xy.txt'
    lst = file_read(file_in)
    print(lst) # Test file read
    for line in line_concat(lst):
        print(line) 
Output:
['xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy'] xxx.xxx.xx.xx:yyyy xxx.xxx.xx.xx:yyyy
xy.txt that i use to test with is:
Output:
xxx.xxx.xx.xx yyyy xxx.xxx.xx.xx yyyy
Reply
#8
(May-04-2019, 07:45 AM)snippsat Wrote: Try to use code tags and not images with code,look at BBCode.
In my example i am running the last part in interactive shell has >>>.
Now you have put all in one function and that will not work as i have written it.
Here a example running as a script,see that need print() when running as a script.
def line_concat(lst):
    temp = zip(lst[::2], lst[::-2])
    return [':'.join(i) for i in temp]

def file_read(file_in):
    with open(file_in) as f:
        lst = [line.strip() for line in f if not line.isspace()]
        return lst

if __name__ == '__main__':
    file_in = 'xy.txt'
    lst = file_read(file_in)
    print(lst) # Test file read
    for line in line_concat(lst):
        print(line) 
Output:
['xxx.xxx.xx.xx', 'yyyy', 'xxx.xxx.xx.xx', 'yyyy'] xxx.xxx.xx.xx:yyyy xxx.xxx.xx.xx:yyyy
xy.txt that i use to test with is:
Output:
xxx.xxx.xx.xx yyyy xxx.xxx.xx.xx yyyy

Here is what I've got. The file, when I open it, is unchanged from before I added the code.
Thank you for the help so far, this stuff can just get confusing

Heres the code now:

Quote:
def line_concat(lst):
    temp = zip(lst[::2], lst[::-2])
    return [':'.join(i) for i in temp]

def file_read(file_in):
    with open(file_in) as f:
        lst = [line.strip() for line in f if not line.isspace()]
        return lst



if __name__ == '__main__':
    with open("ScrapedProxys.txt","w+") as t:
        t.close()
    main()
    file_in = "ScrapedProxys.txt"
    lst = file_read(file_in)
    for line in line_concat(lst):
        f.write(line)


Clear()

input("Press Enter to Exit")

The
Quote:with open("ScrapedProxys.txt","w+") as t:
is to create the file on start
Reply
#9
You use close() that's not needed when use with open and there is no write().
Here how it look if write result to file.
def line_concat(lst):
    temp = zip(lst[::2], lst[::-2])
    return [':'.join(i) for i in temp]

def file_read(file_in):
    with open(file_in) as f:
        lst = [line.strip() for line in f if not line.isspace()]
        return lst

if __name__ == '__main__':
    file_in = 'xy.txt'
    lst = file_read(file_in)
    #print(lst) # Test file read
    with open('xy_new.txt', 'w') as f_out:
        for line in line_concat(lst):
            f_out.write(f'{line}\n')
Reply
#10
(May-04-2019, 08:21 PM)snippsat Wrote: You use close() that's not needed when use with open and there is no write().
Here how it look if write result to file.
def line_concat(lst):
    temp = zip(lst[::2], lst[::-2])
    return [':'.join(i) for i in temp]

def file_read(file_in):
    with open(file_in) as f:
        lst = [line.strip() for line in f if not line.isspace()]
        return lst

if __name__ == '__main__':
    file_in = 'xy.txt'
    lst = file_read(file_in)
    #print(lst) # Test file read
    with open('xy_new.txt', 'w') as f_out:
        for line in line_concat(lst):
            f_out.write(f'{line}\n')


Thank you so much!
After some error on my side of files showing up blank, I got it with your help!

Cheers!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,308 Nov-09-2023, 10:56 AM
Last Post: mg24
  Context-sensitive delimiter ZZTurn 9 1,392 May-16-2023, 07:31 AM
Last Post: Gribouillis
  Read csv file with inconsistent delimiter gracenz 2 1,140 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Delimiter issue with a CSV file jehoshua 1 1,218 Apr-19-2022, 01:28 AM
Last Post: jehoshua
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 2,772 Dec-15-2020, 05:21 PM
Last Post: snippsat
  Iterate 2 large text files across lines and replace lines in second file medatib531 13 5,705 Aug-10-2020, 11:01 PM
Last Post: medatib531
  copy content of text file with three delimiter into excel sheet vinaykumar 0 2,304 Jul-12-2020, 01:27 PM
Last Post: vinaykumar
  How to print string multiple times separated by delimiter Mekala 1 1,865 May-23-2020, 09:21 AM
Last Post: Yoriz
  How to split string after delimiter SriRajesh 1 2,056 Sep-11-2019, 11:25 AM
Last Post: metulburr
  How to split at specified delimiter SriRajesh 5 3,002 Dec-27-2018, 03:43 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020