I'm having a small error trying to delete some files using the OS module in python and I'm a little confused. I'm trying to run the following code:
import arcpy, os
# Set environment settings
arcpy.env.workspace = r"M:\GIS\Oscar\2021\Grid Script\2022\Split Data"
for file in os.listdir(r"M:\GIS\Oscar\2021\Grid Script\2022\Split Data"):
if file.endswith('.lyr') == True:
# Delete previously created layer
print 'Removing previous .lyr files in: '+str(arcpy.env.workspace)
os.remove(file)
else:
print 'No .lyr files were found in: '+str(arcpy.env.workspace)
But running this code throws me this error:
File "C:/Users/fitzpatricko_adm/AppData/Roaming/JetBrains/PyCharmCE2021.2/scratches/scratch_4.py", line 11, in <module>
os.remove(file)
WindowsError: [Error 2] The system cannot find the file specified: 'Layer Data.lyr'
The reason I'm confused is that the file I'm looking for seems to be found when I run this code in my python console:
for file in os.listdir(r"M:\GIS\Oscar\2021\Grid Script\2022\Split Data"):
if file.endswith('.lyr') == True:
print file
Layer Data.lyr
This is probably a silly question, but any help is much appreciated. I had thought that I might be making a rookie error with how I structured my loop's logic, or perhaps my arcpy env variable is being awkward?
For reference, this is what my loop is finding in the directory:
for file in os.listdir(r"M:\GIS\Oscar\2021\Grid Script\2022\Split Data"):
print file
(BNG) 27700.prj
Proj1 2021 5.csv
Proj1 2020 5.sbx
Proj1 2020 5.dbf
Proj1 2020 5.sbn
Proj1 2020 5.shp.xml
Proj2 2021 8.csv
Proj2 2021 5.csv
Proj1 2020 8.csv
Proj2 2020 8.csv
Layer Data.lyr
Proj1 2020 5.prj
Proj2 2020 5.csv
Proj1 2020 11.csv
Proj1 2021 8.csv
Proj1 2020 5.cpg
Proj1 2020 5.shp
Proj1 2021 11.csv
Proj2 2020 11.csv
Proj1 2020 5.shx
Proj1 2020 5.csv
Proj2 2021 11.csv
Thanks for looking!