Jason Rogers
Jason Rogers

Reputation: 869

List to str adding backslash \ to string using str()

I am trying to extract file paths from a txt file. My file says C:\logs. I use

with open(pathfile, "r") as f:
    pathlist = f.readlines()

to produce a list with the path in, and then

path1 = str(pathlist)

to produce the line as a string. The list sees the line as it is in th efile, but te second command puts in an extra backslash: C:\logs.

I then do

os.chdir(path1)

to look at the path and I get the error

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: "['C:\\logs']"

WHY is this? how can I prevent it?

I am looking to have many paths in the file and have the script search each path individually. Is this the best way to do it?

Thank you very much.

Upvotes: 0

Views: 2432

Answers (3)

CodeManX
CodeManX

Reputation: 11855

str(pathlist) casts the list to a string, which results in ['C:\\logs'], which is definately not a valid path.

with open(pathfile, "r") as f:
    for line in f:
        # print the path (=line)
        # strip() removes whitespace as well as the line break '\n' at the end
        print(strip(line))

Or you could do:

for line in f:
    print(line.replace('\\n', ''))

Or:

for line in f:
    if line:
        print(line.splitlines()[0])

Upvotes: 1

mtadd
mtadd

Reputation: 2555

Let's say the contents of pathfile are as follows:

C:\Path1
C:\Path2
C:\Path3

readlines returns a list of all lines in pathfile.

[ 'C:\Path1', 'C:\Path2', 'C:\Path3' ]

Using str on a python list creates a string which is a literal intrepretation of the list parseable by python. Its not what you want.

"[ \"C:\\Path1\", \"C:\\Path2\", \"C:\\Path3\" ]"

What you want is something like

import os

with open(pathfile, "r") as f:
   for line in f.readlines():
      path = line.strip() # strip newline characters from end of line
      os.chdir(path)

Upvotes: 0

mhlester
mhlester

Reputation: 23211

The extra backslash you see is an "escape" character, which is how the representation of the string disambiguates the existing backslash. It's not actually two backslashes

The problem is actually that pathlist is a list, and you're forcing it to be a str. Instead, take the first element of pathlist:

path1 = pathlist[0]

You may also have a line break at the end (another use of escape: \n or \r). To solve that, use .strip()

path1 = pathlist[0].strip()

Upvotes: 3

Related Questions