0

I have a file (sysid.txt) that consist of multiple line of data (systemid and hostname) as follow

0192.4500.0000 uue01.re1                              
0192.4500.0010 ccu01.re1                              
0192.4500.0110 uue02.re1                               
0192.4500.0001 core1.re2                                   

Based from info and help here, the 1st string(numbers) successfully replace as require but the 2nd string(hostname) missing and the output presented in single line when I run the code below.

file1 = open('sysid.txt', 'r')
file2 = open('sysip.txt', 'w')
file1_cont = file1.readlines()
for line in file1_cont:
    line = line.replace('.', '')
    f = itemgetter(slice(0,3), slice(3,6), slice(6,9), slice(9,12))
    line = '.'.join(f(line.replace('.','')))
    line = '{}.{}.{}.{}'.format(*map(int, f(line.replace('.', ''))))
    file2.write(line)
    print(line)

the output of sysip.txt

10.89.0.010.89.0.110.89.0.3210.89.0.3310.89.0.3410.89.0.3510.89.0.64

Read each line, I would like to replace 1st string(numbers) and maintain 2nd string (hostname) as below

192.45.0.0 uue01.re1                              
192.45.0.10 ccu01.re1                              
192.45.0.110 uue02.re1                               
192.45.0.1 core1.re2

How can i manipulate 1st string/numbers and save the output line (file2.write(line)) in new line and at the same time remain the 2nd string as above.

Thank you for your support and guidance.

#

updated list.txt...

System ID      Hostname                                        
0192.4500.0000 uue01.re1                              
0192.4500.0010 ccu01.re1                              
0192.4500.0110 uue02.re1                               
0192.4500.0001 core1.re2 

{master}
chenoi
  • 575
  • 3
  • 8
  • 30

2 Answers2

0

How can i manipulate 1st string/numbers [...] and at the same time remain the 2nd string as above.

It seems you can split the string on the space character before you replace the points, to only modify the part where you need to.

Example:

s = "0192.4500.0010 ccu01.re1                              "
numbers, host = s.split()
numbers = numbers.replace(".", "")
# TODO: fill in appropriate conversions with `numbers` here
print(numbers, host)

The output is:

019245000010 ccu01.re1

For reference:


How can i [...] save the output line (file2.write(line)) in new line

When writing the output to the file, newline characters are not added automatically. You need to add them to the string yourself.

Example:

numbers = "{}.{}.{}.{}".format(*numbers)
line = "{} {}\n".format(numbers, host)
outf.write(line)

Also, it is a good habit to use the with statement to open and eventually close the files.

For reference:

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
  • Not an output OP wanted. – DirtyBit Mar 19 '19 at 07:42
  • @DirtyBit Copying the missing parts from the OP is left as an excercise to the reader. – moooeeeep Mar 19 '19 at 07:44
  • ip, hostname = line.split() print(ip, hostname) ....Im getting error below--> ip, hostname = line.split() ValueError: need more than 1 value to unpack – chenoi Mar 19 '19 at 08:24
  • @chenoi You have a line not adhering to the format, e.g., an empty line or one containing more or less than two words. You might want to add [exception handling](https://docs.python.org/3.7/tutorial/errors.html#handling-exceptions) and [skip such lines](https://docs.python.org/3.7/reference/simple_stmts.html#continue), for example. – moooeeeep Mar 19 '19 at 08:33
0

list.txt:

0192.4500.0000 uue01.re1                              
0192.4500.0010 ccu01.re1                              
0192.4500.0110 uue02.re1                               
0192.4500.0001 core1.re2   

Hence:

def removeZeros(ip):
    # splits the ip by "."
    # converts the words to integeres to remove leading removeZeros
    # convert back the integer to string and join them back to a string
    new_ip = ".".join([str(int(i)) for i in ip.split(".")])
    return new_ip

logFile = "list.txt"
with open(logFile) as f:
    content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]

for line in content:
    line = line[1:].split(" ")[0]
    line =  removeZeros(line).replace(removeZeros(line).split(".", 2)[1],removeZeros(line).split(".", 2)[1][:-2] + ".0")
    print(line)

OUTPUT:

192.45.0.0
192.45.0.10 
192.45.0.110 
192.45.0.1 

EDIT:

If you want to overwrite the new ip list to the same file, you can create two separate lists to store the ips and the text:

logFile = "list.txt"
with open(logFile) as f:
    content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
ipList = []
stList = []
for line in content:
    stList.append(line[1:].split(" ")[1])
    line = line[1:].split(" ")[0]
    line =  removeZeros(line).replace(removeZeros(line).split(".", 2)[1],removeZeros(line).split(".", 2)[1][:-2] + ".0")
    ipList.append(line)
    # print(line)

with open(logFile, "w") as f:
    for index in range(len(ipList)):
        f.write(str(ipList[index]) + " " + str(stList[index]) + "\n")

OUTPUT (from the file):

192.45.0.0 uue01.re1
192.45.0.10 ccu01.re1
192.45.0.110 uue02.re1
192.45.0.1 core1.re2

EDIT 3:

In order to remove the first and last line, use slicing:

Replace this line:

for line in content:

with this:

for line in content[1:-1]:  # after the first and before the last line
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • Hi...I'm getting error below --> stList.append(line[1:].split(" ")[1]) IndexError: list index out of range – chenoi Mar 20 '19 at 07:35
  • @chenoi The above code is tested. Do you have the same data like I do in the above `list.txt`? – DirtyBit Mar 20 '19 at 07:40
  • Hi sir, the list got header and string at the end of the file... when i manually delete the header and last string...and just the data....run code ok...i have updated the list.txt... how can i remove the header and the last line? – chenoi Mar 20 '19 at 08:42
  • @chenoi using slicing, check the Edit 3. – DirtyBit Mar 20 '19 at 08:48
  • 1
    U r the man sir!...i tried using [1:-1] before... but...i add wrongly.... thank goodness u point me to the right point...thank you sir. – chenoi Mar 20 '19 at 08:53
  • @chenoi no worries, you may accept the answer if it helped: https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work cheers! – DirtyBit Mar 20 '19 at 08:53