Adding relative path as aa variable - python-3.x

I want to get user input path and use it as a variable. But still struggle to use it right way. I put root variable for error_log creation in the folder by User input.
root = input("Enter path to music folder: ")
for root, dirs, files in os.walk(root):
for name in files:
if name.lower().endswith(".mp3"):
try:
os.rename(os.path.join(root,name), os.path.join(root,name.replace("_"," ").replace(".MP3",".mp3")))
except:
with open(r"root\Error_mp3_log.txt","a", encoding='UTF-8') as w:
w.write(os.path.join(root, name, "\n"))
w.write('\n')

Related

How to save files to a directory and append those files to a list in Python?

Scenario:
I want to check whether if a directory contains a certain '.png' image file. If so, this image file along with all the other files (with png extension only) gets stored in a different directory. (The solution I am looking for should work in all OS platforms i.e Windows, Unix, etc.) and in a remote server i.e (FTP etc.)
I have tried the following code below:
import os, sys
import shutil
import pathlib
import glob
def search():
image_file = 'picture.png'
try:
arr = [] #List will be used to append all the files in a particular directory.
directory = pathlib.Path("collection") #checks if the collection directory exists.
files = []
#need to convert the PosixPath (directory) to a string.
[files.extend(glob.glob(str(directory) + "/**/*.png", recursive = True))]
res = [img for img in files if(img in image_file)] #checks if the image is within the list of files i.e 'picture.png' == 'collection\\picture.png'
if str(bool(res)): #If True...proceed
print("Image is available in image upload storage directory")
for file in files:
transfer_file = str(file)
shutil.copy(file, 'PNG_files/') #send all the files to a different directory i.e 'PNG_files' by using the shutil module.
arr.append(transfer_file)
return arr
else:
print("image not found in directory")
except OSError as e:
return e.errno
result = search() #result should return the 'arr' list. This list should contain png images only.
However, during execution, the For loop is not getting executed. Which means:
The image files are not stored in the 'PNG_files' directory.
The images are not getting appended in the 'arr' list.
The code above the For loop worked as expected. Can anyone explain to me what went wrong?
There are several issues:
In this line
res = [img for img in files if(img in image_file)] #checks if the image is within the list of files i.e 'picture.png' == 'collection\\picture.png'
you should check the other way around (as written in the comment): image_file in img, e.g. picture.png in collection/picture.png.
str(directory) + "/**/*.png" is not OS independent. If you need this to work on Windows, too, you should use os.path.join(str(directory), '**', '*.png') instead!
This check is incorrect: if str(bool(res)):. It's actually always true, because bool(res) is either True or False, str(bool(res)) is either "True" or "False", but both are actually True, as neither is an empty string. Correctly: if res:.
And finally, you're missing the creation of the PNG_files directory. You need to either manually create it before running the script, or call os.mkdir().

How to choose & save files to a directory with Python 3?

I'm having trouble making a subfolder for files to be stored into after choosing the Parent Folder or directory.
This is my current script:
import os, sys, subprocess, shutil, glob, os.path, csv
#User Chooses Folder or File Path Directory
path_new = filedialog.askdirectory()
def saveData():
serial_number = input('Scan Barcode: ')
folder_name = print('Folder Name:', serial_number)
os.chdir(path_new) #Not sure if this is necessary
if not os.path.exists(path_new):
os.makedirs(path_new)
print ('The data has been stored in the following directory:', path_new)
shutil.move('file_directory/TOTAL.csv', 'chosen_directory/%s'% (serial_number))
shutil.move('file_directory/enviro.csv', 'chosen_directory/%s' % (serial_number))
The script runs, but just not how I would like it to. Does anyone have any recommendations or an alternate solution to creating a folder and selecting it as the directory to have subfolders created and have files transferred into them?
I resolved my issue. If anyone else knows of a "cleaner" way of writing this out please update with a better answer. As of now this does exactly what I want.
Code:
import os, sys, shutil. os.path
path = filedialog.askdirectory()
def saveData():
serial_number = input('Scan Barcode: ')
folder_name = print('Folder Name:', serial_number)
path_new = os.path.join(path, '%s' % (serial_number))
if not os.path.exists(path_new):
os.makedirs(path_new)
shutil.move('C:/files/TOTAL.csv', path_new)
shutil.move('C:/files/enviro.csv', path_new)
print('The data has been stored in the following directory:', path_new)

While loop doesn't work inside my for loop

mi_path = "F:\\releases\\"
validate = False
for dirs, paths, files in os.walk(mi_path):
while not validate:
if str(release_buscar) in str(dirs):
print("Release encontrada", dirs)
break
else:
print("Release no encontrada")
release_buscar = input("Introduce el nombre otra vez:")
validate = False
print("Final del bucle")
I want to list all dirs from a route how I am doing and then find a string in that route. I need to do if string in dirs then make something if that string isn't in, then ask again for a valid string
I get the dirs with os.walk function and it return a string with dirs from the route. Then I want to find a string in a string(dirs).
The problem if what never find the folder, always jump to the else:.
for that you can use os.path.exists("my_dir") and your code gonna be something like
import os
def get_existing_dir():
my_dir = input("Please enter a directory name : ")
while True:
if os.path.exists(my_dir):
return my_dir
my_dir = input("Please enter an existing directory name : ")

Python: Checking file names in a directory one by one

I am asking for user input of a name, and I want to search in the directory of the file with the code whether a file exists that is called the same thing as the inputted name, if yes, then the program asks for a new name, if not, then it will create a file with that name. I am struggling because the code I have written only checks the first file in the directory and doesn't continue with the rest.
The code that I am having the problem with looks something like this:
import os
Name = input("Please enter name for new file")
if Name in os.listdir():
print("Sorry this name already exists, please choose another one")
break
else:
NewFile = open("Name" + ".txt", "w+")
break
You can use glob:
import glob
existing = glob.glob('*.txt')
name = '{}.txt'.format(input("Please enter name for new file"))
if name in existing:
print("Sorry this name already exists, please choose another one")
else:
newfile = open(name, "w+")

Check a folder if it contains anything python3

I need code that's able to check a folder in the same directory as the python script if it contains either folders or files
this code from How to check to see if a folder contains files using python 3 doesn't work
import os
for dirpath, dirnames, files in os.walk('.'):
if files:
print dirpath, 'Contains files or folders'
if not files:
print dirpath, 'Contains nothing'
The folder I'm checking is DeviceTest
Working
Try this code which uses OSError and aslo os.rmdir never directory which are not empty.So we can use this exception to solve the problem
import os
dir_name = "DeviceTest"
try:
os.rmdir(dir_name)
except OSError as exception_name:
if exception_name.errno == errno.ENOTEMPTY:
print("Directory contains files")
else:
print("Directory don't contain files and is empty")
Simple solution
import os
dir_name = "DeviceTest"
if os.listdir(dir_name) == []:
print("Empty")
for path, dirs, files in os.walk(folder):
if (files) or (dirs):
print("NOT EMPTY: " + str(path))
if (not files) and (not dirs):
print("EMPTY : " + str(path))

Resources