I'm trying to pass elements from a list to a for loop and of course am getting the classic error 'argument 1 must be a string not list' - for the os.chdir() function.
Here is a my code, any suggestions as to how I can get around the above error and still pass the elements of my list on to the rest of the script so it loops through each one would be greatly appreciated!!
path= ['C:\\DataDownload\Administrative', 'C:\\DataDownload\Cadastral', 'C:\\Dat开发者_开发技巧aDownload\Development']
for x in path[:]:
os.chdir(path)
#Remove all previous files from the current folder
for file in os.listdir(path):
basename=os.path.basename(file)
if basename.endswith('.DXF'):
os.remove(file)
if basename.endswith('.dbf'):
os.remove(file)
if basename.endswith('.kmz'):
os.remove(file)
if basename.endswith('.prj'):
os.remove(file)
if basename.endswith('.sbn'):
os.remove(file)
if basename.endswith('.sbx'):
os.remove(file)
if basename.endswith('.shp'):
os.remove(file)
if basename.endswith('.shx'):
os.remove(file)
if basename.endswith('.zip'):
os.remove(file)
if basename.endswith('.xml'):
os.remove(file)
You want os.chdir(x)
instead of os.chdir(path)
.
path
is the list containing all the paths (and should thus probably be named paths
), so you can't use it as an argument to chdir
.
First of all, double your backslashes if you want to hardcode the Windows paths this way (otherwise you'll have unexpected behaviour pop up once you have a \t
in your path for example).
No need for copying the list (with path[:]
): for x in path
will do just as well.
No need for explicitely calling os.chdir
...
And the if
clauses are a bit ugly (and hard to maintain); the example can thus be simplified like this:
directories = ['C:\\DataDownload\\Administrative',
'C:\\DataDownload\\Cadastral',
'C:\\DataDownload\\Development']
for directory in directories:
for filename in os.listdir(directory):
base_filename, extension = os.path.splitext(filename)
if extension in ['.DXF','.dbf','.kmz','.prj','.sbn','.sbx',
'.shp','.shx','.zip','.xml']:
os.remove(os.path.join(directory, filename))
It might be helpful to look at the os module documentation.
精彩评论