Below is my code to batch rename pictures inside a given directory
def multi_filename_change():
i = 0
files = askstring('Select your folder', 'Paste your directory path where your images are stored.')
for file in os.listdir(files):
if not file.startswith('.'):
file_name = askstring('Add file name', 'Please enter a name for your files.')
src = file
dst = file_name + str(i) + ".jpg"
os.rename(src, dst)
i += 1
When this is run I get the below error message:
os.rename(src, dst) FileNotFoundError: [Errno 2] No such file or directory: '360007_space-wallpaper-4k.jpg' -> 'test0.jpg'
I cannot seem to solve this and its probably an easy one for you experts :)
Thanks
Source should be appended with existing directory, not just filename
src =files+file
Or
src=os.path.join(files, file)
Related
I'm trying to create a program to rename multiple files at once. This would be through Python, and I realize I'm recreating the wheel but I'm trying to understand what I'm doing wrong. Any help would be greatly appreciated. Program.......
import os
path = "LOCATION"
dir_list = os.listdir(path)
myList = []
for x in dir_list:
if x.endswith(".mp3"):
f1 = x.split("-")
ln1 = f1[0] # Band Name
ln2 = f1[1] # Album Title
ln3 = f1[2] # Track number
ln4 = f1[3] # Song Name
newname = x.join(ln2 + ln3)
os.rename(x, newname)
print(newname)
Your error:
line 14, in <module> os.rename(x, newname) -> FileNotFoundError: [WinError 2] The system cannot find the file specified:
...Is likely due to the path not being included in your os.rename() call, I suggest changing os.rename(x, newname) to os.rename(path + x, path + newname) which will solve that issue.
I also noticed some funky behavior with the way you were grabbing the song information, so if you have any further issues, here's the code I used to debug your original issue which seems to have the result you're going for:
import os
path = "C:\\Users\\Pepe\\Documents\\StackOverflow\\73430533\\"
dir_list = os.listdir(path)
for x in dir_list:
if x.endswith(".mp3"):
# I ignore the ".mp3" to keep the file names clean
nameDetails = x.split('.mp3')[0].split('-')
bandName = nameDetails[0]
albumTitle = nameDetails[1]
trackNumber = nameDetails[2]
songName = nameDetails[3]
newName = f"{albumName} | {trackName}.mp3"
print(f"Renaming \"{x}\" to \"{newName}\"")
os.rename(path + x, path + newName)
here is the simple version of my code:
for filename in os.listdir('excels/'):
print(filename)
df = pd.read_excel(filename)
df.head()
Output is:
RandomExcelData.xlsx
---------------------------------------------------------------------------
FileNotFoundError: [Errno 2] No such file or directory: 'RandomExcelData.xlsx'
What is really happening here? why pandas does not recognize the file name that is clearly there?
I tested this and it works properly:
df = pd.read_excel('excels/RandomExcelData.xlsx')
df.head()
this returns output as intended...
You need to add the path when reading the Excel files:
for filename in os.listdir('excels/'):
print(filename)
df = pd.read_excel('excels/' + filename)
df.head()
You are getting this result because filename is just the filename, not the full path. Try this line instead:
df = pd.read_excel('excels/' + filename)
Or, change the script's working directory to 'excels':
for filename in os.listdir('excels/'):
print(filename)
os.chdir('excels')
df = pd.read_excel(filename)
df.head()
directory = 'data/'
files = [os.path.join(directory, file) for file in os.listdir(directory) if file.endswith('.csv')]
for file in files:
df = pd.read_csv(file)
I have some Python code that I have written that creates a zip file but it writes the file to the location where the Python script is located versus the folder I need it to be written to. How do I structure my code to make it write to the location I need it to?
def get_all_file_paths(directory):
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
for root, subdirectories, files in os.walk(src):
if root != src + 'Errors':
for subdirectory in subdirectories:
if subdirectory != 'A' and subdirectory != 'B' and subdirectory != 'C':
print(subdirectory)
folderName = subdirectory
print('The folder name is', folderName)
print(os.path.join(root, subdirectory))
filePath = os.path.join(root, subdirectory)
file_paths = get_all_file_paths(filePath)
print('Following files will be zipped: ')
for file_name in file_paths:
print(file_name)
with ZipFile(folderName +'.zip', 'w') as zip:
for file in file_paths:
zip.write(file, os.path.relpath(file, root))
zip.close()
print('All files zipped successfully!')
I'm walking through a directory structure finding all files with the .shp extension and storing them in a dictionary. However, some files are named the same, how do I store files of the same name in a dictionary without overwriting? Appending the file structure to the name would be acceptable in this case. How is that done?
Current 'working' code:
def get_all_shp(mydir):
# layers = []
data = {}
for root, dirs, files in os.walk(mydir):
for file in files:
try:
if file.endswith(".shp"):
shp = os.path.join(root, file)
# layers.append(shp)
path = root + "/" + file
# print("path: " + path)
data[file] = gpd.read_file(path)
except:
pass
def get_all_shp(mydir):
# layers = []
data = {}
for root, dirs, files in os.walk(mydir):
for file in files:
try:
if file.endswith(".shp"):
shp = os.path.join(root, file)
# layers.append(shp)
path = root + "/" + file
# print("path: " + path)
data[path] = gpd.read_file(path)
except:
pass
I was working on a file converting function for a xlxs -> csv format. I was able to make the function work when I specified the exact file, but I'm running into issues when I try to iterate the process over a dir folder. Below is the code:
def ExceltoCSV(excel_file, csv_file_base_path):
workbook = xlrd.open_workbook(excel_file)
## get the worksheet names
for sheet_name in workbook.sheet_names():
print('processing - ' + sheet_name)
## extract the data from each worksheet
worksheet = workbook.sheet_by_name(sheet_name)
## create a new csv file, with the name being the original Excel worksheet name; tidied up a bit replacing spaces and dashes
csv_file_full_path = csv_file_base_path + sheet_name.lower().replace(" - ", "_").replace(" ","_") + '.csv'
csvfile = open(csv_file_full_path, 'w')
## write into the new csv file, one row at a time
writetocsv = csv.writer(csvfile, quoting = csv.QUOTE_ALL)
for rownum in range(worksheet.nrows):
writetocsv.writerow(
list(x.encode('utf-8') if type(x) == type(u'') else x for x in worksheet.row_values(rownum)
)
)
csvfile.close()
print(sheet_name + ' has been saved at - ' + csv_file_full_path)
## Paths as strings
p = r'//Network/TestingFolder/'
nf_p = r'//Network/TestingFolder/CSV_Only/'
## directory reference
directory = r'//Network/TestingFolder/' # for os.listdir() function below
file_list = []
## for iterating over directory and spitting out the paths for each file { to be used in conjunction
with ExceltoCSV() }
for filename in os.listdir(directory):
if filename.endswith(".xlsx"): # or filename.endswith(".csv")
file_path = os.path.join(directory, filename)
file_list.append(file_path)
else:
continue
for paths in file_list:
print(paths)
ExceltoCSV(paths, nf_p)
My error is occurring with the line >> csvfile = open(csv_file_full_path, 'w')
Error is: FileNotFoundError: [Errno 2] No such file or directory