How to write a script to delete multiple files in python? [duplicate] - python

This question already has answers here:
Delete multiple files matching a pattern
(9 answers)
Closed 2 years ago.
I am new to scripting and trying to write a python script to remove a few files.. Here is the path Multiple scripts/script*
Main directory: Multiple scripts
sub directories: script1
script2
script3
In each script in subdirectories, I have file consists of mem. Since I don't know what they start with or their extension now I would like to write a script to search all the subdirectories and delete files that consists of mem.
I tried using the following code but did not work for me
import os
if Multiple scripts/scripts*
os.remove(*/mem*)
else:
print ("file does not exists")
And also please help me with how to write a script to delete files with multiple names (/mem, /name) at a time. Any help would be appreciated... Thank you

If I'm understanding your question correctly, I think you'll want the glob module. Something like
import os
import glob
for fname in glob.iglob("./*/mem*"):
print("Removing "+fname)
os.remove(fname)
Before you run that loop, though, I'd say run it first without the last line, to see what it would do, and make sure that that's what you want.

Related

Rename part of the name in any files or directories in Python [duplicate]

This question already has answers here:
How to rename a file using Python
(17 answers)
Closed 3 years ago.
I have a root folder with several folders and files and I need to use Python to rename all matching correspondences. For example, I want to rename files and folders that contain the word "test" and replace with "earth"
I'm using Ubuntu Server 18.04. I already tried some codes. But I'll leave the last one I tried. I think this is really easy to do but I don't have almost any knowledge in py and this is the only solution I have currently.
import os
def replace(fpath, test, earth):
for path, subdirs, files in os.walk(fpath):
for name in files:
if(test.lower() in name.lower()):
os.rename(os.path.join(path,name), os.path.join(path,
name.lower().replace(test,earth)))
Is expected to go through all files and folders and change the name from test to earth
Here's some working code for you:
def replace(fpath):
filenames = os.listdir()
os.chdir(fpath)
for file in filenames:
if '.' not in file:
replace(file)
os.rename(file, file.replace('test', 'earth'))
Here's an explanation of the code:
First we get a list of the filenames in the directory
After that we switch to the desired folder
Then we iterate through the filenames
The program will try to replace any instances of 'test' in each filename with 'earth'
Then it will rename the files with 'test' in the name to the version with 'test' replaced
If the file it is currently iterating over is a folder, it runs the function again with the new folder, but after that is done it will revert back to the original
Edited to add recursive iteration through subfolders.

Is there a way to view the directory that a file is in using python? [duplicate]

This question already has answers here:
Find the current directory and file's directory [duplicate]
(13 answers)
Closed 3 years ago.
For a project I am working on in python, I need to be able to view what directory a file is in. Essentially it is a find function, however I have no idea how to do this using python.
I have tried searching on google, but only found how to view files inside a directory. I want to view directory using a file name.
To summarise: I don't know the directory, and want to find it using the file inside it.
Thanks.
In Python, the common standard libraries for working with your local files are:
os.path
os
pathlib
If you have a path to a file & want it's directory, then we need to extract it:
>>> import os
>>> filepath = '/Users/guest/Desktop/blogpost.md'
>>> os.path.dirname(filepath) # Returns a string of the directory name
'/Users/guest/Desktop'
If you want the directory of your script, the keyword you need to search for is the "current working directory":
>>> import os
>>> os.getcwd() # returns a string of the current working directory
'/Users/guest/Desktop'
Also check out this SO post for more common operations you'll likely need.
Here's what I did:
import os
print(os.getcwd())

Read files sequentially in order [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 9 years ago.
I have a number of files in a folder with names following the convention:
0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ...
I need to read them one by one and manipulate the data inside them. Currently I open each file with the command:
import os
# This is the path where all the files are stored.
folder path = '/home/user/some_folder/'
# Open one of the files,
for data_file in os.listdir(folder_path):
...
Unfortunately this reads the files in no particular order (not sure how it picks them) and I need to read them starting with the one having the minimum number as a filename, then the one with the immediate larger number and so on until the last one.
A simple example using sorted() that returns a new sorted list.
import os
# This is the path where all the files are stored.
folder_path = 'c:\\'
# Open one of the files,
for data_file in sorted(os.listdir(folder_path)):
print data_file
You can read more here at the Docs
Edit for natural sorting:
If you are looking for natural sorting you can see this great post by #unutbu

Python subprocess.call - adding a variable to subprocess.call [duplicate]

This question already has answers here:
Why does passing variables to subprocess.Popen not work despite passing a list of arguments?
(5 answers)
Closed 1 year ago.
I'm trying to write a simple program in Python that takes all the music files from my Downloads folder and puts them in my Music folder. I'm using Windows, and I can move the files using the cmd prompt, but I get this error:
WindowsError: [Error 2] The system cannot find the file specified
Here's my code:
#! /usr/bin/python
import os
from subprocess import call
def main():
os.chdir("C:\\Users\Alex\Downloads") #change directory to downloads folder
suffix =".mp3" #variable holdinng the .mp3 tag
fnames = os.listdir('.') #looks at all files
files =[] #an empty array that will hold the names of our mp3 files
for fname in fnames:
if fname.endswith(suffix):
pname = os.path.abspath(fname)
#pname = fname
#print pname
files.append(pname) #add the mp3 files to our array
print files
for i in files:
#print i
move(i)
def move(fileName):
call("move /-y "+ fileName +" C:\Music")
return
if __name__=='__main__':main()
I've looked at the subprocess library and countless other articles, but I still have no clue what I'm doing wrong.
The subprocess.call method taks a list of parameters not a string with space separators unless you tell it to use the shell which is not recommended if the string can contain anything from user input.
The best way is to build the command as a list
e.g.
cmd = ["move", "/-y", fileName, "C:\Music"]
call(cmd)
this also makes it easier to pass parameters (e.g. paths or files) with spaces in to the called program.
Both these ways are given in the subprocess documentation.
You can pass in a delimited string but then you have to let the shell process the arguments
call("move /-y "+ fileName +" C:\Music", shell=True)
Also in this case for move there is a python command to do this. shutil.move
I'm not answering your question directly, but for such tasks, plumbum is great and would make your life so much easier. subprocess's api is not very intuitive.
There could be several issues:
fileName might contain a space in it so the move command only sees a part of filename.
if move is an internal command; you might need shell=True to run it:
from subprocess import check_call
check_call(r"move /-y C:\Users\Alex\Downloads\*.mp3 C:\Music", shell=True)
To move .mp3 files from Downloads folder to Music without subprocess:
from glob import glob
from shutil import move
for path in glob(r"C:\Users\Alex\Downloads\*.mp3"):
move(path, r"C:\Music")

os.unlink multiple file in python [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Deleting files by type in Python on Windows
How can I delete all files with the extension ".txt" in a directory? I normally just do
import os
filepath = 'C:\directory\thefile.txt'
os.unlink(filepath)
Is there a command like os.unlink('C:\directory\*.txt') that would delete all .txt files? How can I do that?
Thanks!
#!/usr/bin/env python
import glob
import os
for i in glob.glob(u'*.txt'):
os.unlink (i)
should do the job.
Edit: You can also do it in "one line" using map operation:
#!/usr/bin/env python
import glob
import os
map(os.unlink, glob.glob(u'*.txt'))
Use the glob module to get a list of files matching the pattern and call unlink on all of them in a loop.
Iterate through all files in C:\directory\, check if the extension is .txt, unlink if yes.

Categories

Resources