Home > Software engineering >  Python file name on create
Python file name on create

Time:12-11

I'm trying to learn files in Python and I have this set of codes, this code used to create a normal file in the development server which I used to play, but in production, the files output as '2022-12-10 10:40:14.599578 00:00.webm' , enclosed within single quotes, now I'm not sure if I manually remove this single quotes, the file will be a valid WebM file or not? and If I'm doing something wrong, how can I improve this?

    time = timezone.now()

    with open(path.join(path.dirname(path.realpath(__file__)), f'{time}.webm'), 'wb') as file:
        file.write(decode_string)
        file.close()

CodePudding user response:

Some modern directory listing software will enclose filenames having spaces with single (or double) quotes, for convenience. This does not mean the filename itself starts and ends with such quotes. To demonstrate:

$ echo "Hello world" > /tmp/foo\ bar
$ echo "no_spaces_in_file" > /tmp/foo_bar
$
$ ls /tmp
'foo bar'   foo_bar
$ cat "/tmp/foo bar"
Hello world
$ cat /tmp/'foo bar'
Hello world
$ cat /tmp/'foo_bar'
no_spaces_in_file
$ cat /tmp/foo_bar
no_spaces_in_file

This depends on the directory-listing software, and if you're using ls, this can be avoided with the -N flag:

$ find /tmp -type f
/tmp/foo bar
/tmp/foo_bar
$
$ ls -1 /tmp
'foo bar'
foo_bar
$
$ ls -1 -N /tmp
foo bar
foo_bar

By default, most shells will handle such quotes before passing the arguments to the command (as demonstrated with cat earlier), but when running in a different context (e.g. inside python), this does not happen:

>>> print(open("/tmp/foo bar").read())
Hello world

>>> print(open("/tmp/'foo bar'").read())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: "/tmp/'foo bar'"

While Unix/Linux filesystems usually can handle filenames of all types, it is a good practice to avoid special characters and spaces, to prevent confusion or compatibility bugs/issues. A quick fix can be replacing spaces with underscores, like so:

f'{time}.webm'.replace(" ", "_")
  • Related