Reputation: 51
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
Reputation: 1024
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
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
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
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
Reputation: 3940
Try doing:
fileName = line.strip().split("FILE:")[1].strip().replace("'", "")
Upvotes: 0