Search code examples
python-3.xstringstring-formatting

Python3 string formatting with . in front missing


I am trying to write a file transfer program and trying to make a list of files to skip processing: The script itself, and the VI backup and swap files (server.py~ and .server.py.swp)

I cannot get the proper name of the vi swap file, .server.py.swp, the dot at the beginning is missing and I get server.py.swp

I first create the list with .server.py.swp hardcoded (I had the others hardcoded, but removed them after I got the string formatting for them working). I then add the script file and backup file using string formatting. I append string "test" for debugging purposes and as a separator. Finally, I try to add the swap file with string formatting using two different methods and it gets added with the leading . at the front missing.

To run the code in server.py I am referring to, I have a client.py I am in the process of developing.

client.py

import os, socket
port = 7777
host = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

server.py

import os, socket

port = 7777
host = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)

while True:
    clientsocket, address = s.accept()
    print(f"Connection from {address} has been established!!!")
    # https://stackoverflow.com/questions/4934806
    File = os.path.realpath(__file__)
    dir = os.path.dirname(File)
    os.chdir(dir)
    server_files = os.listdir(".")
    skip = [".server.py.swp"]
    # https://pythonguides.com/python-get-filename-from-the-path/
    skip.append(os.path.basename(File))
    skip.append(os.path.basename(f"{File}~"))
    skip.append(f"test")
    skip.append(os.path.basename(f".{File}.swp"))
    skip.append(os.path.basename(".{}.swp".format(File)))
    print(f"Skip:   {skip}")

# !End

I get incorrect output on the server

Skip: ['.server.py.swp', 'server.py', 'server.py~', 'test', 'server.py.swp', 'server.py.swp']

My desired output would be something like

Skip: ['.server.py.swp', 'server.py', 'server.py~', 'test', '.server.py.swp', '.server.py.swp']

Am I missing something? I tried escaping the . by putting in \. to no avail.

EDIT: I aim for this to be cross-platform, but for now I am developing and testing this one on Windows.


Solution

  • Given that File appears to be a qualified path, not just a file name, prefixing with . before calling basename does nothing; if File is C:\foo\bar.py (would print with extra \s) or /foo/bar.py or even ../relative/bar.py, prefixing with a . puts it before the final directory separator (\ or /), and it gets stripped by basename. If you want to prefix the file name with ., add it after stripping directories, e.g.:

    skip.append("." + os.path.basename(f"{File}.swp"))
    

    or

    skip.append(".{}.swp".format(os.path.basename(File)))