如何基于逗号分割文件行并连接新字符串

时间:2019-06-23 05:34:13

标签: python

我有一个文件,其中包含以下行, 文件位于/ tmp / file

            cat /tmp/file
            server1,server2
            server4,server4

我想将每一行都连接到新词“ .com”,因此如下所示。 当我隐瞒并拆分它不起作用时,请指导

        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)

结果:

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

预期:                 server1.com,server2.com                 server3.com,server4.com

1 个答案:

答案 0 :(得分:2)

id

此代码可以进行很多优化。但这是为了更好地理解