TL;DR: text file contains strings that represent backslash escapes; how do I use them as input to os.stat()
?
I've an input file input.txt
:
./with\backspace
./with\nnewline
Processing them with simple loop doesn't work:
>>> import os
>>> with open('input.txt') as f:
... for line in f:
... os.stat(line.strip())
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
FileNotFoundError: [Errno 2] No such file or directory: './with\\backspace'
Using .decode("unicode_escape")
as suggested in another question works only partially - the first line in the file fails, the second with \n
doesn't.
Sidenote: The input filenames have ./
and I know I can just use os.listdir('.')
and iterate over files till I find the right ones. That's not my objective. The objective is processing filenames that contain backslash escapes from a file.
Additional test:
>>> import os
>>> with open('./input.txt') as f:
... for l in f:
... os.stat(l.strip().decode('unicode_escape'))
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
AttributeError: 'str' object has no attribute 'decode'
>>> with open('./input.txt') as f:
... for l in f:
... try:
... os.stat(l.strip().encode('utf-8').decode('unicode_escape'))
... print(l.strip())
... except:
... pass
...
os.stat_result(st_mode=33188, st_ino=1053469, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1536468565, st_mtime=1536468565, st_ctime=1536468565)
./with\nnewline
Writing explicit string with os.fsencode()
works:
>>> os.stat(os.fsencode('with\x08ackspace'))
os.stat_result(st_mode=33188, st_ino=1053465, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1536468565, st_mtime=1536468565, st_ctime=1536468565)
However, with multiple variations on the same command, I still can't read the string from the file such that os.stat()
accepts it.
>>> with open('./input.txt') as f:
... for l in f:
... os.stat(os.fsdecode( bytes(l.strip(),'utf-8').decode('unicode_escape').encode('latin1') ) )
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
FileNotFoundError: [Errno 2] No such file or directory: './with\x08ackslash'