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!

3
  • re.sub docs.python.org/3/library/re.html#re.sub Commented Feb 11, 2019 at 20:33
  • 1
    Loop over the lines instead of the delnode. E.g.: for line in file: Commented Feb 11, 2019 at 20:33
  • And you get the /1/1 in a new line because you are currently a newline character. Use delnode.strip() to remove it Commented Feb 11, 2019 at 20:35

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

That works! Thank you for your help!
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.