so I'm here again with my handsome script, that should download data from my second computer using TCP sockets. I've got a couple of questions, that I was not able to find on google.
Question n.1:
First of all, is there a way, to check if a string is ending without extension? I found, that I can use .endswith()
, but it doesn't work the way I would like to, because I would have to define every extension that exists in the World, and that wouldn't be so practical.
EDIT: I just found the solution for that second question, right away when I was reading this post.
To deal with filenames in a cross-platform way, you should use the os
module.
Getting the extension from a filename is supported by the os.path.splitext
function:
# '.file' extension
filepath = "this/is/a.file"
_, ext = os.path.splitext(filepath)
print(len(ext))
# No extension
filepath = "this/is/afile"
_, ext = os.path.splitext(filepath)
print(len(ext))
will output:
5
0
5
for the extension of .file
and 0
for there not being an extension. Thus you can check if a filename has an extension with a function like:
def has_ext(filepath):
_, ext = os.path.splitext(filepath)
return len(ext) > 0