简体   繁体   English

python中确保字符串适合作为文件名的优雅方式?

[英]Elegant way in python to make sure a string is suitable as a filename?

I want to use a user-provided string as a filename for exporting, but have to make sure that the string is permissible on my system as a filename.我想使用用户提供的字符串作为导出的文件名,但必须确保该字符串在我的系统上是允许的作为文件名。 From my side it would be OK to replace any forbidden character with eg '_'.从我的角度来看,可以用例如“_”替换任何禁止的字符。

Here I found a list of forbidden characters for filenames .在这里,我找到了filenames 的禁用字符列表

It should be easy enough to use the str.replace() function, I was just wondering if there is already something out there that does that, potentially even taking into account what OS I am on.使用str.replace()函数应该很容易,我只是想知道是否已经有一些东西可以做到这一点,甚至可能考虑到我使用的操作系统。

pathvalidate is a Python library to sanitize/validate a string such as filenames/file-paths/etc. pathvalidate是一个 Python 库,用于清理/验证字符串,例如文件名/文件路径/等。

This library provides both utilities for validation of paths:该库提供了用于路径验证的两个实用程序:

import sys
from pathvalidate import ValidationError, validate_filename

try:
    validate_filename("fi:l*e/p\"a?t>h|.t<xt")
except ValidationError as e:
    print("{}\n".format(e), file=sys.stderr)

And utilities for sanitizing paths:以及用于清理路径的实用程序:

from pathvalidate import sanitize_filename

fname = "fi:l*e/p\"a?t>h|.t<xt"
print("{} -> {}".format(fname, sanitize_filename(fname)))

A better solution may be for you to store the files locally using generated filenames that are guaranteed to be unique and file system safe (any UUID generator would do, for example).更好的解决方案可能是您使用生成的文件名在本地存储文件,这些文件名保证唯一且文件系统安全(例如,任何 UUID 生成器都可以)。 Maintain a simple database that maps between the original filename and the UUID for later use.维护一个简单的数据库,在原始文件名和 UUID 之间映射以供以后使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM