1

I have a file which has lines like below, Files are in /tmp/file

            cat /tmp/file
            server1,server2
            server4,server4

I want to concatenate each line to new word ".com" so it will look like below. When i covert this and split it doesn't work , Please guide

        newfile = server1.com,server2.com
                  server3.com,server4.com



            with open('/tmp/file', 'r') as file1:
                   newline = ''
                   for line in file1:
                       y = line.split()
                       print(y)
                   for line in y:
                       z = str(y).split(',')
                       print(z)
                       newline = str(z)+".com".join('' )
                   print(newline)

Results :

            ['server1,server2']
            ['server3,server4']
            ["['server3", "server4']"]
            ["['server3", "server4']"]

Expected : server1.com,server2.com server3.com,server4.com

4
  • ','.join([f"{j}.com" for i in p.read_text().splitlines() for j in i.split(',')])(where p is pathlib.Path object.) Commented Jun 23, 2019 at 5:37
  • Please add explanation . This seems not working. ','.join([f"{j}.com" for i in p.read_text().splitlines() for j in i.split(',')]) File "<ipython-input-100-f0280c232ed5>", line 1 ','.join([f"{j}.com" for i in p.read_text().splitlines() for j in i.split(',')]) ^ SyntaxError: invalid syntax Commented Jun 23, 2019 at 5:51
  • Which version of python you are using? Commented Jun 23, 2019 at 5:55
  • Python3 , I do have 2.7 as well. In [110]: with open('/tmp/file', 'r') as file1: ...: for i in file1.read().splitlines(): ...: print(i) ...: for j in i.split(','): ...: k = j.splitlines() ...: abc = ",".join([k+".com"]) ...: print(abc) Error: TypeError: can only concatenate list (not "str") to list Commented Jun 23, 2019 at 6:04

1 Answer 1

2
with open('/tmp/file', 'r') as r:
    for line in r:
        newline = line.strip()
        newline = newline.split(',')
        for i in range(len(newline)):
            newline[i] = newline[i] + ".com"
        newline = ",".join(newline)
        print newline

This code can be optimized a lot. But this is for better understanding

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.