1

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.

7 Answers 7

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

@mile.k: it is only removing ending single quote
That's because of the whitespace after FILE:, try replacing "FILE:" with "FILE: ". I just edited that in.
Until there're few spaces after FILE:.
1

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" 

Comments

0

Try doing:

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

Comments

0

You could use string replace method

str.replace("'","")

Comments

0

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]

Comments

0
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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.