How to create source string from string variable in python?

You create a raw string from a string as follows:

test_file=open(r'c:\Python27\test.txt','r')

How do you create a raw variable from a string variable like

path = 'c:\Python27\test.txt'

test_file=open(rpath,'r')

Since I have a file path:

file_path = "C:\Users\b_zz\Desktop\my_file"

When I do this:

data_list = open(os.path.expandvars(file_path),"r").readlines()

I get:

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    scheduled_data_list = open(os.path.expandvars(file_path),"r").readlines()
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\x08_zz\\Desktop\\my_file'
+4
source share
3 answers

There is no such thing as a raw string after creating a string in the process. Ways to specify the string ""and r""exist only in the source code itself.

, "\x01" , 0x01, r"\x01" , 4 '0x5c', '0x78', '0x30', '0x31'. (, python 2 ).

, ( gui, ) - escape- , . ( -, , * nix):

% cat > test <<EOF                                             
heredoc> \x41
heredoc> EOF
% < test python -c "import sys; print sys.stdin.read()"
\x41
+6

( : '\ a',\b ','\f ','\n ','\r ','\t ','\v escape- ):

def str_to_raw(s):
    raw_map = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'}
    return r''.join(i if ord(i) > 32 else raw_map.get(ord(i), i) for i in s)

:

>>> file_path = "C:\Users\b_zz\Desktop\fy_file"
>>> file_path
'C:\\Users\x08_zz\\Desktop\x0cy_file'
>>> str_to_raw(file_path)
'C:\\Users\\b_zz\\Desktop\\fy_file'
+1

ndpu .

( Python 2 ):

_dRawMap = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'}

def getRawGotStr(s):
    #
    return r''.join( [ _dRawMap.get( ord(c), c ) for c in s ] )

, , ndpu . , .

0

Source: https://habr.com/ru/post/1525624/


All Articles