Pregunta

I need to convert a file list into string and save it to db.
a file list like:

[
  # [name, length]
  # name is in bytes
  ['111.txt', '1024'],
  ['english.txt', '2048'],
  ['some CJK words.log', '2048'],
  ....
]

note:

  1. all file name is legal.
  2. file name is not user input

now, I use:

if fs:
    files = []
    file_names = fs[0]
    file_lengths = fs[1]
    for i in xrange(len(file_names)):
        files.append(file_names[i] + '\#' + file_lengths[i])
    files = '\n'.join(files)

    save_to_mysql(files)

Because I think a file name which be present in bytes would not have \n and \#,but I am not quite sure.Is it safe to use \# and \n in my situation?

¿Fue útil?

Solución

The proper solution for this is to use a character that cannot appear in the texts.

But if this is not possible and it this character does appear in the text, then it have to be marked somehow, that is, escaped.

There are already solutions that to exactly that: you can use the C string syntax or XML or JSON or YAML...

But if you feel particular lazy, I've sometimes used the character U+0080, because it not used anywhere. But note taht if in the future you want to encode a list of strings as an element of your list... you'll have a problem! Also, you'll have to check the input strings, in case some malicious user injects this character U+0080 into your strings and start breaking things.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top