0

I need to open a file that have multiple absolute file directories.

EX:

    Layer 1 = C:\User\Files\Menu\Menu.snt

    Layer 2 = C:\User\Files\N0 - Vertical.snt

The problem is that when I try to open C:\User\Files\Menu\Menu.snt python doesn't like \U or \N

I could open using r"C:\User\Files\Menu\Menu.snt" but I can't automate this process.

file = open(config.txt, "r").read()
list = []

for line in file.split("\n"):
    list.append(open(line.split("=",1)[1]).read())

It prints out:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 33-34: malformed \N character escape
2
  • does list.append(open(r"{}".format(line.split("=",1)[1])).read()) work? Commented Apr 27, 2017 at 12:36
  • 1
    SyntaxError happens at compile time, not at runtime. The error does not match your code. Commented Apr 27, 2017 at 12:37

2 Answers 2

2

The backslash character \ is used as an escape character by the Python interpreter in order to provide special characters.

For example, \n is a "New Line" character, like you would get from pressing the Return key on your keyboard.

So if you are trying to read something like newFolder1\newFolder2, the interpreter reads it as:

newFolder1
ewFolder2

where the New Line character has been inserted between the two lines of text.

You already mentioned one workaround: using raw strings like r'my\folder\structure' and I'm a little curious why this can't be automated.

If you can automate it, you could try replacing all instances of a single backslash (\) with a double backslash (\\) in your file paths and that should work.

Alternatively, you can try looking in the os module and dynamically building your paths using os.path.join(), along with the os.sep operator.

One final point: You can save yourself some effort by replacing:

list.append(open(line.split("=",1)[1]).read())

by

list = open(line.split("=",1)[1]).readlines()

Sign up to request clarification or add additional context in comments.

2 Comments

Your code replacement suggestion will result in only the last file's lines being contained in the list.
Also, "the interpreter reads it as" is not entirely true, depending on where the data comes from.
0

here is my solution:

file = open("config.txt", "r").readlines()
list = [open(x.split("=")[1].strip(), 'r').read() for x in file]

readlines creates a list that contains all lines in file, there is no need to split the whole string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.