I want to perform some data cleaning on all the files in the same folder as my script that fit a naming convention.
The data cleaning I am fine with, but it’s just the same folder that I am struggling with.
Previous working code:
JavaScript
x
3
1
import glob
2
for filename in glob.glob('C:/Users/<me>/Downloads/New Folder/Forecast and Inventory *.xlsx'):
3
Current code:
JavaScript
1
3
1
import os
2
for filename in os.getcwd() + 'Forecast and Inventory *.xlsx':
3
I get the error code
No such file or directory: 'C'
Do I need to do some kind of replacement to turn the s into /s? As the code suggests, I want all files that start with ‘Forecast and Inventory’.
Thank you!
Advertisement
Answer
You are iterating through a string.
Since os.getcwd() + 'Forecast and Inventory *.xlsx'
is the string "C://**working-dir/Forecast and Inventory *.xlsx"
So on the first iteration filename
is the string 'C'
.
For example
JavaScript
1
3
1
for filename in os.getcwd() + 'Forecast and Inventory *.xlsx':
2
print(filename)
3
WIll return
JavaScript
1
5
1
"C"
2
":"
3
"/"
4
5
You just need to put the path inside glob.glob
JavaScript
1
3
1
for filename in glob.glob(os.getcwd() + 'Forecast and Inventory *.xlsx'):
2
# do something
3