Linocomp
Linocomp

Reputation: 51

How to ignore single quotes which extracting file names in python

I have a file(main.cpp) containing list of other files. The format is as below:

FILE: 'addition.cpp'
FILE: 'matrix.cpp'
FILE: 'rate_of_interest.cpp'

My code is as below:

lines=mainfile.read().splitlines()
for i, line in enumerate(lines):
    line = line.strip()
    if "FILE:" in line:
        fileName = line.strip().split("FILE:")[1].strip()
    else 
       print "Invalid file" 

This prints as below

'addition.cpp'
'matrix.cpp'
'rate_of_interest.cpp'

But I want as below,

addition.cpp
matrix.cpp
rate_of_interest.cpp

How can I remove single quotes? I am new to python, tried various way, but not happening.

Upvotes: 1

Views: 1298

Answers (7)

Renae Lider
Renae Lider

Reputation: 1024

A regex solution FILE:\s*'(.+)'

import re

data = """FILE: 'addition.cpp'
          FILE: 'matrix.cpp'
          FILE: 'rate_of_interest.cpp'
       """

for line in re.findall(r"FILE:\s*'(.+)'", data):
    print(line)

If you want to find filenames that are empty, change the + to * in the regex code above.

Upvotes: 0

mike.k
mike.k

Reputation: 3447

fileName = line.strip().split("FILE: ")[1].strip("'")

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

with open("in.cpp") as f:
    for line in  f:
        if line.startswith("FILE:"):
            print(line.split()[1].strip("'"))

Output:

addition.cpp
matrix.cpp
rate_of_interest.cpp

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174736

You don't need to strip any character just do splitting on single quotes.

if "FILE:" in line:
    print(line.split("'")[1])
else 
   print "Invalid file" 

Upvotes: 1

rassa45
rassa45

Reputation: 3550

If you have your list of filenames, do it like this.

#Parse Parse Parse until you get variable filenames (list)
filenames = #Some list of filenames
filenames = [name.replace("\"", "").replace("'", "") for name in filenames]

Upvotes: 0

The6thSense
The6thSense

Reputation: 8335

You could use string replace method

str.replace("'","")

Upvotes: 0

Nhor
Nhor

Reputation: 3940

Try doing:

fileName = line.strip().split("FILE:")[1].strip().replace("'", "")

Upvotes: 0

Related Questions