Michael H.
Michael H.

Reputation: 93

os.path.abspath(__file__) give invalid locaiton and adds extra \'s to the file path

I am working on a program that will edit all local files ending in a csv extension. When I call the location of the directory and then change directory I get an error. The error is due to extra \'s being added to the path. How can I call the path without these extra \'s?

I've looked around and there are similar issues but every example I see is for a hard written location and not a movable one.

import os
import glob
import sys


path = os.path.abspath(__file__)
extension = '.csv'
os.chdir(os.path.abspath(__file__))
result = glob.glob('*'.format(extension))
print(path)
print(result)

Upvotes: 0

Views: 785

Answers (1)

Mason Caiby
Mason Caiby

Reputation: 1934

os.chdir() needs a directory not a file which is what you are giving it. try changing os.chdir(os.path.abspath(__file__)) to os.chdir(os.path.dirname(path))

import os
import glob
import sys

__file__ = 'test.txt'

path = os.path.abspath(__file__)
print(path)
extension = '.csv'
os.chdir(os.path.dirname(path))
result = glob.glob('*'.format(extension))
print(path)
print(result)

Upvotes: 2

Related Questions