- Remove specific element from Python array/list by the element itself.
sampleList = ["1", "2", "3", "4", "one", "two", "three", "four"]
for e in sampleList:
if e == "two": sampleList.remove(e)
print(sampleList)
- For the codes above the output will be.
["1", "2", "3", "4", "one", "three", "four"]
- In Python you can know whether an element in a
os.listdir()
array is a file or a directory/folder by using this codes.
os.path.isfile("example_file.txt") # This will return True.
os.path.isdir("example_folder") # This will return False.
- Here is a Python codes on how to normalize path name,
os.path.normpath("path/name/here")
.
- Normalize is necessary to remove unnecessary symbol.
- After the string is normalized as a path string then I can do other operation.
- For example to find the last file/folder in the string path you can use this Python codes,
os.path.basename(normalized_path)
. With this command I can return the last entry of a path.
- For example,
a/b/c/d.text
will return d.txt
.
- Example on how to know a file extension from a path string.
fileName, fileExt = os.path.splitext(fldrOrFl)
print(fileName)
print(fileExt)
- Example codes on how to get a parent directory from the string path.
upperDir = None
for s in targDirArray:
if upperDir == None: upperDir = s
else: upperDir = upperDir + "/" + s
upperDirNorm = os.path.normpath(upperDir)
print(upperDirNorm)
- Example of reading lines in a file without encryption.
lines = md.readlines() # Line returned without new lines.
# Line returned without new lines.
# This is the preferred way.
lines = md.read().splitlines()