0

Imagine you want to remove a file in a directory which is Excel, but only if it is the same name as a PDF in the same directory.

Have tried the following:

import os

    #if both excel and pdf, remove excel
    directory = r"C:\Users\Max12\Desktop\xml\git\yourubl\attachments\75090058\Status\Verwerking"
    pdffile = os.path.join(directory, '.pdf')
    excelfile = os.path.join(directory, '.xlsx')
    
    if pdffile == excelfile:
        os.remove(excelfile)

Please help

Max
  • 493
  • 2
  • 9

3 Answers3

1

You can use pathlib to accomplish that straightforward:

import pathlib

directory = pathlib.Path(r"C:\Users\Max12\Desktop\xml\git\yourubl\attachments\75090058\Status\Verwerking")

for f in directory.glob('*.xlsx'):
    if f.with_suffix('.pdf').exists():
        f.unlink()
Corralien
  • 109,409
  • 8
  • 28
  • 52
0

Replace your if with the following if condition and try,

if os.path.exists(pdffile) and os.path.exists(excelfile):
    os.remove(excelfile)

Your code doesn't mention anything about file names. You can find all pdf filenames in a directory using glob Reference

Aurum
  • 53
  • 1
  • 2
  • 11
  • Thank you for your comment! Tried it and nothing happens so I think there may be an error here: pdffile = os.path.join(directory, '.pdf') excelfile = os.path.join(directory, '.xlsx') – Max Jul 06 '21 at 12:06
  • Whats the error message? and is the directory variable a filename or a folder name? – Aurum Jul 06 '21 at 12:08
0

For all files in your directory you may want to use sets:

pdf = set([f[:-4] for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f)) and f.endswith('.pdf')])
xl = set([f[:-5] for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f)) and f.endswith('.xlsx')])

to_del = [str(i)+'.xlsx' for i in list(a&b)]
for f in to_del:
  os.remove(os.path.join(mypath, f))
zanga
  • 612
  • 4
  • 20