hey all hope someone can help!
Im using the below to find the most recent file downloaded in the specified directory. I need to be able to rename the file from how it comes to a specic name - any help would be appreciated.
import glob
import os
download_path = f'C:\\Users\\{os.getlogin()}\\Downloads'
list_of_files = glob.glob(f"{download_path}\\*")
latest_file: str = max(list_of_files, key=os.path.getctime)
print(latest_file)
os.rename("latest_file", "??????????")
the file needs to be called sf-admin-term
Thanks!
ext = latest_file.split('.')[-1]
os.rename(latest_file, f"{download_path}/new_file.{ext}")
Related
Im trying to open a csv file as followed
My ipynb-file is in the following directory -> /data/filename.ipynb
where as my csv file is in the following directory -> /data/preprocessed/processed_data.csv
When i try to open the file with the following code:
df = pd.read_csv('/preprocessed/processed_data.csv')
I get an exception that the file doesn't exist. Somehow I think I didn't quite understand how the directories work. Please help, thanks.
try this-
df = pd.read_csv('preprocessed/processed_data.csv')
Try using the os module with a relative path:
import os
filename = os.path.join(os.path.dirname(__file__),'path/to/file/processed_data.csv')
df = pd.read_csv(filename)
my way of getting the name of the next file in a folder is just terrible but works.I would like to remove the requirement of calling the os.listdir function as it is slow in large folders but dont know how. Any help is welcome.
Note:
Fullpathtoimagefile is the old file
changeimage is the name of a function that gets the next file
def nextfile(self):
folder, filename = os.path.split(fullpathtoimagefile)
filelist = os.listdir(folder)
nextfile = filelist.index(filename) + 1
nextfilename = filelist[nextfile]
changeimage(os.path.join(folder, nextfilename))
tl;dr More efficient way to get the full name of the next file in a folder
Maybe you can work with this one out.
[(os.path.join(folder, d), d, os.path.isdir(os.path.join(folder, d ))) for d in os.listdir(folder)]
simple code..
import os
arq = (os.listdir(".")) # "." = directory name
for file in arq:
print(file)
Another example:
import os
arq = (os.listdir("."))
for file in arq:
if (os.path.splitext(file)[1] == ".jpg"): #if a JPG file, do something
print(file)
This kind of smells like an instance of the XY problem. It looks like you're trying to iterate over images in a folder - in that case, use the pathlib module (it's been around since Python 3.4):
from pathlib import Path
for path in Path("path/to/folder/with/images").glob("*.jpg"):
print(path)
I am new to Python coding so here a question. I want to find files that are called "untitled" with any kind of extension, e.g. jpg, indd, psd. Then rename them to the date of the current day.
I have tried the following:
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if file.endswith("untitled.*"):
print(file)
When I run the script, nothing happens.
You might find the glob function more useful in this situation:
import glob
for file in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
print(file)
Your function does not print anything as there are probably no files ending with .* in the name. The glob.glob() function will carry out the file expansion for you.
You can then use this to do your file renaming as follows:
import glob
import os
from datetime import datetime
current_day = datetime.now().strftime("%Y-%m-%d")
for source_name in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
path, fullname = os.path.split(source_name)
basename, ext = os.path.splitext(fullname)
target_name = os.path.join(path, '{}{}'.format(current_day, ext))
os.rename(source_name, target_name)
A Python datetime object can be used to get you a suitable timestamp.
Python string comparator does not support wildcards. You can search for "untitled." anywhere in the text:
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if "untitled." in file:
print(file)
keep in mind that this will include any file that has "untitled." at any location of the file.
try with this approach
import os
directoryPath = '/Users/shirin/Desktop/Artez'
lstDir = os.walk(directoryPath)
for root, dirs, files in lstDir:
for fichero in files:
(filename, extension) = os.path.splitext(fichero)
if filename.find('untitle') != -1: # == 0 if starting with untitle
os.system('mv '+directoryPath+filename+extension+' '+directoryPath+'$(date +"%Y_%m_%d")'+filename+extension)
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if(file.startswith("untitled")):
os.rename(file, datetime.date.today().strftime("%B %d, %Y") + "." + file.split(".")[-1])
I have a file test.py which works good. see code:
import os
import shutil
import re
for root, dirs, files in os.walk("../config/"):
for file in files:
print os.path.join(root, file)
if file.endswith(".txt") and file.startswith("default_"):
file_name = os.path.basename(os.path.join(root, file))
file_name = re.sub(r'default_','',file_name)
shutil.copy(os.path.join(root, file),os.path.join(root,file_name))
but when I wrapped the code into a function and put it in another file config.py. And I called the function in another file as config.copy_default_files(), it doesn't work. So I put a raw_input() in the end of the function to see if the function is executed, and it did print 'miao', but it didn't print out the list of files. And no file is generated or copied.
I am so so confused.Can someone explain it to me please? Any help would be great appreciated. Let me know if you need more information on it. Manythanks!
import os
import shutil
import re
def copy_default_files(work_dir = "../config/"):
for root, dirs, files in os.walk(work_dir):
for file in files:
print os.path.join(root, file)
if file.endswith(".txt") and file.startswith("default_"):
file_name = os.path.basename(os.path.join(root, file))
file_name = re.sub(r'default_','',file_name)
shutil.copy(os.path.join(root, file),os.path.join(root,file_name))
raw_input('miao')
return 0
Defining the function is not enough. You also need to call it:
copy_default_files()
or
config.copy_default_files()
(depending on whether you're running config.py as a script or importing it as a module).
I am trying to create a script where all the file extensions are changed from .bmp to .jpg. There have been some helpful answers I have found but I still can't get my script to work. If anyone had any suggestions on what I might need to change, it would be greatly appreciated. The script doesn't come up with any errors but none of the file extensions in the folder change.
import os, glob, sys
folder = '\\stsosage\...\LegalCardsTest'
for filename in glob.iglob(os.path.join(folder, '*.bmp')):
os.rename(filename, filename[:-4] + '.jpg')
try this:
import os
def walk_dir(targetdir,topdown=True):
for root, dirs, files in os.walk(targetdir, topdown):
for name in files:
os.rename(targetdir+name, targetdir+name.replace(".bmp",".jpg"))
walk_dir(FOLDER_PATH_END_WITH_\)
My Code:
import os
os.chdir(input("Enter dir: "))
endv = input("File extension before: ")
endn = input("File extension after: ")
for s in os.listdir(pfad):
if "."+endv in s:
try:os.rename(s,s.replace("."+endv,"."+endn)
except BaseException e:print(e)
Hope it works fine.
filename is only the file name and not the entire path that you need to provide to you mv function.
Try to concat folder with filename in your mv command.