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.
Related
This question already has answers here:
How do i search directories and find files that match regex?
(4 answers)
Closed 8 months ago.
In the directory there are multiple images with names:
I want to delete all images with "340" in it using a python code.
Assuming that the images are in desktop/images/
I'm not sure why you need to use Python and can't just use your shell (in bash it would just be rm desktop/images/*340*)
But in Python I think the shortest way would be
import os, glob
for file in glob.glob("desktop/images/*340*"):
os.remove(file)
or even:
import os, glob
[os.remove(file) for file in glob.glob("desktop/images/*340*")]
You can use this example, you'll have to adjust the code for your correct directory:
import os
import re
for file in os.listdir("Desktop/Images"):
if re.search("340.*?\.jpg$", file):
os.remove("Desktop/Images/" + file)
print("Deleted " + file)
else:
print("No match for " + file)
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.
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())
This question already has answers here:
How to find newest file with .MP3 extension in directory?
(6 answers)
Closed last year.
I have many files in a folder. Like:
tb_exec_ns_decile_20190129.csv
tb_exec_ns_decile_20190229.csv
tb_exec_ns_decile_20190329.csv
So i just want to pick latest file:
tb_exec_ns_decile_20190329.csv
import glob
import os
latest_csv = max(glob.glob('/path/to/folder/*.csv'), key=os.path.getctime) #give path to your desired file path
print latest_csv
Since your csv files share a common prefix, you can
simply use max on the list of files. Assuming you are located
in the directory with your files and tb_exec_ns_decile_20190329.csv
has the latest date:
>>> import glob
>>> max(glob.glob('tb_exec_ns_decile_*.csv'))
'tb_exec_ns_decile_20190329.csv'
This question already has answers here:
How do I remove/delete a folder that is not empty?
(22 answers)
Closed 5 years ago.
i wish to delete a local directory if it already exists. below is my code:
import sys
import os
from pyspark import SparkContext
from pyspark import SparkConf
conf=SparkConf().setAppName('pyspark')
sc=SparkContext(conf=conf)
data=sc.textFile('file:///home/cloudera/Downloads/SAN_SALES_EXTRACT_TRANS_LEVEL_D0906.txt')
datamap=data.map(lambda x: ((str(x.split(',')[1]).strip(),int(x.split(",")[0])),float(x.split(",")[10])))
datagrouped=datamap.reduceByKey(lambda x,y: x+y)
if (os.path.exists("file:///home/cloudera/Downloads/store_perday_rev")):
os.remove("file:///home/cloudera/Downloads/store_perday_rev")
else:
datagrouped.sortByKey().saveAsTextFile("file:///home/cloudera/Downloads/store_perday_rev")
#for i in datagrouped.sortByKey().take(20):
# print(i)
It doesn't delete the directory. What am i doing wrong?
Try os.rmdir() instead.
os.remove() only works for a file path, not for a directory.
You can try these options .
import os
os.rmdir("C:/test/delete/pydelete")
i am able to remove the folder.If you have the data in this folder then you need to call.
shutil.rmtree()
are your trying to remove the directory or the file?
if you are trying to remove the directory please refer to the following link:
How do I remove/delete a folder that is not empty with Python?
Also refer to the python docs:
https://docs.python.org/2/library/os.html