1

I am very new to python, i am trying to write a script which opens a file, read the file do some custom function for me and store it in project location. Meanwhile i am facing trouble to read the file line by line and find the string in between the two forward slashes. like in the example shown below i want the script to read the "string between the slashes".

"element / read_this_string /... "

I did go through some hints provided online, as in to use Regular expression or use split function. I found split() rather easy to implement.

I would really appreciate if someone could help me with this problem i am stuck with. I am sure its a simple one but i am wasting too much time on this.

preetham
  • 21
  • 1
  • 6
  • can you post your code? – Haifeng Zhang Jan 29 '16 at 16:30
  • 2
    _"I found split() rather easy to implement."_ So you're saying you already have a solution for your problem, and the solution uses `split`, and the solution was easy? Just use that then. Or do you mean something else...? – Kevin Jan 29 '16 at 16:31
  • @Kevin...problem is i am having trouble implementing the solution using the split()....i am not sure how to work around for the solution !! – preetham Jan 29 '16 at 16:34
  • @haifzhan .....This is what i have tried with "data = infile.read().split('element / /') , where 'infile' is the file created... – preetham Jan 29 '16 at 16:36

2 Answers2

2

You can pass a delimiter to split, to clean the spaces you can them use the strip method..

s = "element / read_this_string /... "

string_in_slashes = s.split('/')[1].strip()

string_in_slashes
Out[13]: 'read_this_string'
canesin
  • 1,967
  • 2
  • 18
  • 30
0

To open a file in python, you can use python's with statement, which will handle file closing. and the for loop will take care of reading the file line by line.

with open("file.txt") as f:
    for line in f:
        if len(line.split("/")) > 1:
            print(line.split("/")[1])
slcjordan
  • 96
  • 3
  • @slcjordan....thanks for ur help, but i am getting a syntaxError: Invalid syntax. for the line "print line.split("/")[1]"......not sure why !! – preetham Jan 29 '16 at 16:55
  • So I did somethink like this " file = line.split("/")[1]" , but this is throwing me an error saying "IndexError: list index out of range" – preetham Jan 29 '16 at 17:01
  • So that's probably because not every line has two slashes... See my edit – slcjordan Jan 29 '16 at 17:32