0

I am wanting to shorten my code. Thus far for all my files in:

C:\1A.csv
C:\2A.csv
C:\3\3A.csv
C:\4\4A.csv
C:\5\5A.csv
C:\6\6A.csv
C:\7\7A.csv
C:\8\8A.csv
C:\9\9A.csv
C:\10\10A.csv
C:\11\11A.csv
C:\12\12A.csv

I have:

try:
    os.remove("C:\1A.csv")
 except OSError:
    pass
 try:
    os.remove("C:\2A.csv")
 except OSError:
    pass
#etc,,

Which works great, but it creates lengthy code.

The following also works great:

del_list = ['file1.csv', 'file2.csv', 'file3.csv'];

for fd in del_list:
    try:
        os.remove(os.path.join(my_dir, fd))
    except OSError:
        pass

Though this is limited generally to one folder.  

1 Answers1

1

Starting from python3.5+, you can use glob and do a recursive traversal of your directories. Assuming you want to remove all CSV files, you can do this:

root = os.getcwd()
for file in glob.glob('*/**/*.csv'):
    try:
        os.remove(os.path.join(root, file))
    except OSError:
        ...
cs95
  • 379,657
  • 97
  • 704
  • 746
  • How do I apply this to for example: C:\1A.csv, C:\2A.csv. I suppose I will have to remove all other crucial csv files elsewhere –  Nov 05 '17 at 04:30
  • @DallasClov If the depth is fixed, you can use `*/*/*.csv` (for depth equal to 2), etc. – cs95 Nov 05 '17 at 04:32
  • For me that doesn't seem to delete the csv files. For example in: C:\W1\9\P\1 B I have csv files which are not deleted –  Nov 05 '17 at 04:35
  • @DallasClov Then, I think the best solution is to use os.walk. – cs95 Nov 05 '17 at 04:36
  • @DallasClov Take a look at this [link](https://stackoverflow.com/questions/35315873/python-3-travel-directory-tree-with-limited-recursion-depth) and modify it for your own particular use case. – cs95 Nov 05 '17 at 04:38
  • Alternatively I could just put all the files in one folder. Copy them to a new location. And handle all removing files for this job through that one folder eliminating the need. This would help shorten the code immensely as there is no easy way to delete multiple files from multiple directories without producing huge code. On separate jobs I can micro handle any deletion. –  Nov 05 '17 at 04:48
  • @DallasClov If you can, then you can simply use `os.listdir` on the directory and that would be enough. – cs95 Nov 05 '17 at 04:49