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. 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()
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"
.
Or even better, switch to using the subprocess module. Here you can for example use the subprocess.check_output
function which escapes arguments automatically:
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?