简体   繁体   English

python处理目录中带有空格的文件名

[英]python handle filenames with whitespace in a directory

I have a directory with files that have whitespace in their names, I have a python script that loads these files and runs the tail -n1 command on them, but since there is a whitespace in the name, it fails. 我有一个目录,文件名中带有空格,我有一个python脚本加载这些文件并在文件上运行tail -n1命令,但是由于名称中包含空格,因此失败。 for eg. 例如

I have a dirctory with the following file 我有以下文件的目录

data from_10_13_2014 09_00_45.json

and my script contains the following line line = os.popen("tail -n1 %s" % files).read() 并且我的脚本包含以下行line = os.popen("tail -n1 %s" % files).read()

as of now I get the following error 截至目前,我收到以下错误

tail: cannot open ‘/home/dataserver/Development/Test/data’ for reading: No such file or directory
tail: cannot open ‘from_10_13_2014’ for reading: No such file or directory
tail: cannot open ‘09_00_45.json’ for reading: No such file or directory

The workaround I have now is replacing whitespace with _ is there any way I can do it without renaming the files? 我现在的解决方法是用_替换空格,是否可以在不重命名文件的情况下进行操作?

Try "tail -n1 %r" instead, it will use the string representation of the string, ie tail -n1 "data from_10_13_2014 09_00_45.json" . 尝试使用"tail -n1 %r"代替,它将使用字符串的字符串表示形式,即tail -n1 "data from_10_13_2014 09_00_45.json"

Or even better, switch to using the subprocess module. 甚至更好的是,切换到使用子流程模块。 Here you can for example use the subprocess.check_output function which escapes arguments automatically: 例如,您可以在此处使用subprocess.check_output函数,该函数自动转义参数:

tail_line = subprocess.check_output(["tail", "-n1", files])

I'd recommend you to not use white space at all in file names, it always end up breaking scripts in the end. 我建议您不要在文件名中完全使用空格,因为它最终最终会破坏脚本。 Maybe you can write a second script that normalizes your file names? 也许您可以编写第二个脚本来规范您的文件名?

Replace 更换 with \\ \\ in your files . 在您的files So a backslash + space. 所以反斜杠+空格。

The problem is that you're depending on popen to parse the command line for you, and of course, it uses whitespace to do some of the parsing. 问题是您依靠popen来为您解析命令行,当然,它使用空格来进行某些解析。 A better solution is to build up a list of individual arguments so that no command line parsing has to happen. 更好的解决方案是建立单个参数的列表,这样就不必进行命令行解析。

The easiest way to do that is to use subprocess.check_output : 最简单的方法是使用subprocess.check_output

line = subprocess.check_output(["tail", "-n1", "/tmp/junk.py"])

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

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