In Windows, using Python 2.7, the contents of a file are read and certain lines from that file are (after being prepended with a string "D:\abcddev\") put into a list called FilePathList. These lines are paths to files, for example:
D:\abcddev\toeblog/folderX/fileA.h
D:\abcddev\toeblog/folderY/fileB.h
You will notice that the paths contain a mixture of forward and backward slashes. There is unfortunately nothing I can do about that, that's how they are created and I only have access to them after that.
I want to check if a certain path is found in the list. The path contains all backward slashes.
So, continuing the present example, I want to check if the following is in the list above:
D:\abcddev\toeblog\folderY\fileB.h
As you can see, this string contains all backward slashes.
So my problem is how to check for equality regardless of whether the slash is a forward or backward slash.
My idea was to convert all the members of the FilePathList to backward slash separated paths and put these into a new list NormalizedFilePathList, and then to search that list for the path I wish to find.
So this is my code:
# Declare list
NormalizedFilePathList = []
# Add backward slash separated lines to NormalizedFilePathList
for file in FilePathList:
NormalizedFilePathList.append (os.path.normpath(file))
# Display the contents of NormalizedFilePathList
for file in NormalizedFilePathList
print file
# Create the string to be searched for
test_file = 'D:\abcddev\toeblog\folderY\fileB.h'
# Search for the string in NormalizedPathFileList
if test_file in NormalizedFilePathList:
print "Found test_file"
else:
print "Did not find test_file"
Here is the output of the above:
D:\abcddev\toeblog\folderX\fileA.h
D:\abcddev\toeblog\folderY\fileB.h
Did not find test_file
Why does this not work? There is obviously a match for 'D:\abcddev\toeblog\folderY\fileB.h'.
I tried a few things in my perplexity to clarify matters, as follows:
Printed out the strings in the NormalizedPathFileList using repr() to see if there were any hidden characters preventing a match being found. No, there were not.
Created artificially a new list that I populated manually and searched that instead.
ManualList = ['D:\abcddev\toeblog\folderX\fileA.h','D:\abcddev\toeblog\folderY\fileB.h']
for file in ManualList
print file
# Search for the string in ManualList
if test_file in ManualList:
print "Found test_file"
else:
print "Did not find test_file"
Here was the output:
D:\abcddev oeblog\folderX\fileA.h
D:\abcddev oeblog\folderY\fileB.h
Found test_file
As you can seem there is a tab character in the middle of the line. That is because the string contains '\t'
If I print out the test_file, for the same reason, I also see:
D:\abcddev oeblog\folderY\fileB.h
This explains why the search works when I create a string manually.
So the question is how to escape the \t character in the test_file string ?
Note that whatever code I write must also work in Linux.