1

I'm new to Python so please bear with me. I have a text file named names.txt. The contents of that file are:

6,pon01.bf:R1.S1.LT1.PON10.ONT12
10,pon01.bf:R1.S1.LT1.PON10.ONT16
11,pon01.bf:R1.S1.LT1.PON10.ONT17
12,pon01.bf:R1.S1.LT1.PON10.ONT18

I need to be able to replace the "R", "S", "LT", "PON" and "ONT" with a "/", remove everything else and add "/1/1" to each line. The end result should look like this:

1/1/1/10/12/1/1,
1/1/1/10/16/1/1,
1/1/1/10/17/1/1,
1/1/1/10/18/1/1,

Below is my code:

import os
import re
import sys




file = open("/home/Scripts/names.txt", "r")
delnode = file.readline()

port = "/1/1"

for line in delnode:

   delnode = delnode.split('R')[-1]
   delnode = delnode.replace(".S", "/").replace(".LT", "/").replace(".PON", "/").replace(".ONT", "/")

print delnode + port

file.close()

The output of this script is:

1/1/1/10/12
/1/1

It only reads the first line in the text file. Appreciate any help!

Joost
  • 3,609
  • 2
  • 12
  • 29

2 Answers2

1

You are iterating over the first line with readlines(), just iterate over the file and strip() every line to skip the \n at end of lines.

file = open("/home/Scripts/names.txt", "r")
port = "/1/1"
for line in file:
   line = line.strip().split('R')[-1]
   line = line.replace(".S", "/").replace(".LT", "/").replace(".PON", "/").replace(".ONT", "/")
   print line + port
Rolando cq
  • 588
  • 4
  • 13
1

This wil read all file at once and split it into lines into one list.

file.read().split()

This list you can then iterate line by

import os
import re
import sys


file = open("/home/Scripts/names.txt", "r")
for delnode in file.read().split():
    port = "/1/1"

    # Splitting delnode, you want to get second half of text, therefore index 1 (0 -> 1st index, 1-> 2nd index)
    delnode = delnode.split('R')[1] # [-1] also works, but you are taking the last item
    delnode = delnode.replace(".S", "/").replace(".LT", "/").replace(".PON", "/").replace(".ONT", "/")

    print delnode + port
file.close()

In console:

1/1/1/10/12/1/1
1/1/1/10/16/1/1
1/1/1/10/17/1/1
1/1/1/10/18/1/1
>>> 

NOTE:

I only modified your solution, so you dont have hard time understanding what has happened

Martin
  • 3,333
  • 2
  • 18
  • 39