How to delete a specific PYTHON file

Asked

Viewed 118 times

0

I’m learning Python and I’m trying to make a code where I list two folders, compare the items in common. Getting the result I have to delete the item from the old folder and move the item from the new folder to the old one, however I am not able to delete the file listed by the result of the folder intersection :/

#listagem de diretorios
pastaOld = 'C:/Users/administrador/Desktop/Backups/BackOld/'
pastaNew = 'C:/Users/administrador/Desktop/Backups/BackNew/'
serv = 'C:/Users/administrador/Desktop/Server/'

old = os.listdir(pastaOld)
new = os.listdir(pastaNew)
server = os.listdir(serv)


#interseção dos nomes
firstOld = [old.strip().split(' ')[0] for old in old]
firstNew = [new.strip().split(' ')[0] for new in new]
firstServer = [server.strip().split(' ')[0] for server in server]


interNew = list(set(firstOld).intersection(firstNew))
interServer = list(set(firstNew).intersection(firstServer))

2 answers

0

From what I saw your code has some unnecessary parts, I removed and updated. As you said you are trying to move the files between two folders I deleted that from code:

serv = 'C:/Users/administrador/Desktop/Server/'
server = os.listdir(serv)

We don’t need that either:

#interseção dos nomes
firstOld = [old.strip().split(' ')[0] for old in old]
firstNew = [new.strip().split(' ')[0] for new in new]
firstServer = [server.strip().split(' ')[0] for server in server]

Updated code:

import os
import shutil

pastaOld = 'C:/Users/administrador/Desktop/Backups/BackOld/'
pastaNew = 'C:/Users/administrador/Desktop/Backups/BackNew/'

#pegando a lista de arquivos dentro de cada pasta
old = os.listdir(pastaOld)
new = os.listdir(pastaNew)

print('old: {}'.format(old))
print('new: {}'.format(new))

#fazendo a interseção de cada pasta e imprimindo
inter = list(set(old).intersection(new))
print('intersection: {}'.format(inter))

# removendo os items da pasta antiga
[os.remove(pastaOld + item) for item in inter]

# movendo os arquivos da pasta new para a pasta old
[shutil.move(pastaNew + item, pastaOld + item) for item in new]

I hope it helps you!

0

Hello, I believe the way to remove python files is like this:

import os
os.remove("caminho/nome_do_arquivo.extensao")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.