I wanted to ask the forum how can I delete multiple files in a folder using Python. I tried using the import os module along with os.unlink() module, but it doesn't work. Any help would be greatly appreciated.
Most likely it's because the filename used in the os.unlink(filename) isn't a full path to the file (os.listdir() just returns a sequence of filenames). You probably need to use os.path.join() to prefix the 'c:\\users\\user1' folder to it first.
Something along these lines:
import os
folder = 'c:\\users\\user1\\Pictures'
for filename in os.listdir(folder):
if filename.endswith('.txt'):
os.unlink(os.path.join(folder, filename))
Related
In multiple folders I have a file called _status.json
e.g.:
C:\Users\Me\.fscrawler\Folder1\_status.json
C:\Users\Me\.fscrawler\Folder2\_status.json
....
C:\Users\Me\.fscrawler\*\_status.json
I want to write a short python code, to delete all those files.
I already tried the following code, but it does not work. I dont know why, but I think the solution is pretty easy
import os
os.remove(C:\Users\Me\.fscrawler\*\_status.json)
You will have to walk through all the subfolders to find and delete the file.
for root, dirs, files in os.walk(folder_path):
for name in files:
if name == '_status.json':
#delete the file
I would look into the glob module, and use it to find the files:
example:
import glob
relative_path_to_files = glob.glob('**/_status.json', recursive=True)
then you can operate on the list as you wish :)
Edit:
relative_path_to_files is a list, so you have to iterate over its elements and operate on them:
here is a complete example to find all _status.json in the current directory and its sub-tree recursively:
import glob
import os
for f in glob.glob('**/_status.json', recursive=True):
os.remove(f)
I've already posted here with the same question but I sadly I couldn't come up with a solution (even though some of you guys gave me awesome answers but most of them weren't what I was looking for), so I'll try again and this time giving more information about what I'm trying to do.
So, I'm using a program called GMAT to get some outputs (.txt files with numerical values). These outputs have different names, but because I'm using them to more than one thing I'm getting something like this:
GMATd_1.txt
GMATd_2.txt
GMATf_1.txt
GMATf_2.txt
Now, what I need to do is to use these outputs as inputs in my code. I need to work with them in other functions of my script, and since I will have a lot of these .txt files I want to rename them as I don't want to use them like './path/etc'.
So what I wanted was to write a loop that could get these files and rename them inside the script so I can use these files with the new name in other functions (outside the loop).
So instead of having to this individually:
GMATds1= './path/GMATd_1.txt'
GMATds2= './path/GMATd_2.txt'
I wanted to write a loop that would do that for me.
I've already tried using a dictionary:
import os
import fnmatch
dict = {}
for filename in os.listdir('.'):
if fnmatch.fnmatch(filename, 'thing*.txt'):
examples[filename[:6]] = filename
This does work but I can't use the dictionary key outside the loop.
If I understand correctly, you try to fetch files with similar names (at least a re-occurring pattern) and rename them. This can be accomplished with the following code:
import glob
import os
all_files = glob.glob('path/to/directory/with/files/GMAT*.txt')
for file in files:
new_path = create_new_path(file) # possibly split the file name, change directory and/or filename
os.rename(file, new_path)
The glob library allows for searching files with * wildcards and makes it hence possible to search for files with a specific pattern. It lists all the files in a certain directory (or multiple directories if you include a * wildcard as a directory). When you iterate over the files, you could either directly work with the input of the files (as you apparently intend to do) or rename them as shown in this snippet. To rename them, you would need to generate a new path - so you would have to write the create_new_path function that takes the old path and creates a new one.
Since python 3.4 you should be using the built-in pathlib package instead of os or glob.
from pathlib import Path
import shutil
for file_src in Path("path/to/files").glob("GMAT*.txt"):
file_dest = str(file_src.resolve()).replace("ds", "d_")
shutil.move(file_src, file_dest)
you can use
import os
path='.....' # path where these files are located
path1='.....' ## path where you want these files to store
i=1
for file in os.listdir(path):
if file.endswith(end='.txt'):
os.rename(path + "/" + file, path1 + "/"+str(i) + ".txt")
i+=1
it will rename all the txt file in the source folder to 1,2,3,....n.txt
I have ~60 subdirectories in a single directory. Each of these contain thousands of files, but they all contain a file named test_all_results.txt.
What I would like to do is to rename each test_all_results.txt file so that it now has the name:
foldername_all_results.txt
What is the best way to do this?
Easily accomplished using Python os interface.
Assuming you are currently in the main directory:
import os
#get a list of all sub directories
subdir = os.listdir()
for dir in subdir:
if os.path.isdir(dir): #check if directory
os.chdir(dir) #move to sub directory
os.rename('test_all_results.txt', 'foldername_all_results.txt')
os.chdir('..') #return to main directory
Using python in Linux, make this:
import os
os.system("mv old_name.txt new_name.txt")
You can automatize with a loop, renaming all filenames.
You can do:
(change your code accordingly)
import os
# current directory is the target
direct = "."
for path, dirs, files in os.walk(direct):
for f in files:
if os.path.splitext(f)[0] == "test_all_results.txt":
os.rename(os.path.join(path, f), os.path.join(path, "foldername_all_results.txt"))
There's an answer that tells you to use the os.system() method, if you do decide to call Linux commands from Python, I'd advise that you use the subprocess module instead.
Here's how you'd run the mv command with two arguments using subprocess.call:
import subprocess
subprocess.call(["mv", "filename.txt", "new-name.txt"])
INFO: here's an old (but relevant) article that explains why it's dangerous to use these methods.
Good luck.
I have two directories:
dir = path/to/annotations
and
dir_img = path/to/images
The format of image names in dir_img is image_name.jpg.
I need to create empty text files in dir as: image_name.txt, wherein I can later store annotations corresponding to the images. I am using Python.
I don't know how to proceed. Any help is highly appreciated. Thanks.
[Edit]: I tried the answer given here. It ran without any error but didn't create any files either.
This should create empty files for you and then you can proceed further.
import os
for f in os.listdir(source_dir):
if f.endswith('.jpg'):
file_path = os.path.join(target_dir, f.replace('.jpg', '.txt'))
with open(file_path, "w+"):
pass
You can use the module os to list the existing files, and then just open the file in mode w+ which will create the file even if you're not writing anything into it. Don't forget to close your file!
import os
for f in os.listdir(source_dir):
if f.endswith('.jpg'):
open(os.path.join(target_dir, f.replace('.jpg', '.txt')), 'w+').close()
I am having trouble checking a directory for all files of a certain filetype in python, .wav to be specific.
I have tried a few different methods to solve the problem but can't seem to tackle it. Is there any way in python to check a directory like this?
this will make a list of all the filenames and then check if they end with .wav
import os
listdirectory = os.listdir(".") # gets the name of all files in your dir
for filename in listdirectory:
if filename.endswith(".wav"): # check each of the files for whether or not they end in .wav
import os
files = os.listdir(path) #returns a list of files in the given directory
for filename in files:
if filename.endswith(".wav"):
doSomething
Use iglob:
import glob
search_for = '/foo/bar/*/*.wav'
for i in glob.iglob(search_for):
print(i)