Export in each loop in their corresponding folder? - python

I have a list with directories.
shapelist
that has:
['C:\\Users\\user\\Desktop\\etg\\v1\\ASTENOT\\ASTENOT.shp',
'C:\\Users\\user\\Desktop\\etg\\v2\\ASTENOT\\ASTENOT.shp',
'C:\\Users\\user\\Desktop\\etg\\v3\\ASTENOT\\ASTENOT.shp',
'C:\\Users\\user\\Desktop\\etg\\v4\\ASTENOT\\ASTENOT.shp']
I want in each loop to use each ASTENOT from the list above which resides in a separate folder.
I have solved this part.
The issue is how to export each outcome in the corresponding folder where each input (each ASTENOT in every loop used) is located.
Example:
I am using this specific function in the loop.
arcpy.FeatureToLine_management(['ASTENOT'],'ASTENOT_lines')
The ['ASTENOT] position is for the input and
the 'ASTENOT_lines' is for the output of the function.
How can I make the output exported in the folder of each corresponding input?
Example: the ASTENOT_lines of the first loop to be exported in the v1\\ASTENOT\\ location the second in v2\\ASTENOT\\ and so on.
My attempt:
for i in shapelist:
arcpy.FeatureToLine_management([i],'ASTENOT_lines')
but exports everything in the current working directory and not in their corresponding folders of their inputs in each loop.

You can pass an absolute path to the FeatureToLine_management method.
The absolute path can be generated by simply replacing ASTENOT.shp in the input path with ASTENOT_lines.
So you can change your code to
for i in shapelist:
outputfile = i.replace('ASTENOT.shp', 'ASTENOT_lines')
arcpy.FeatureToLine_management([i], outputfile)

Related

How do you find Discord.exe using python?

I'm trying to find the Discord.exe using python so I can start it automatically,
the problem is the only solutions I've found is to get the full path, which it changes quite a bit,
meaning I'd have to update my code every single time Discord updates.
Navigate to the discord root folder, which is constant, in windows it'll be something like C:\Users\your_name\AppData\Local\Discord, than you can use os.walk("."), it'll return a generator to all the folders down the folder tree, so you can convert this into a list using list(os.walk(".")), as yo only want the folders on your current locantion you use the 0th index of this list, and as you want the folders you'll get the second index, the result will be this list(os.walk("."))[0][1], now you just need to find the folder that the executable is located which is called "app-version", so we can do a simple iteration to grab this folder, in the and the code will be something like:
#code to reach root folder
folders = list(os.walk("."))[0][1]
folder = ""
for f in folders:
if f[:3] == "app":
folder = f
#navigate to folder and execute the Discord.exe

Python: Making a folder with incrementing number depending on existing folders with same name

When someone runs the python script,I want to create a folder named ID + '1' and subsequently next time if someone runs the script again it should put next number i.e. ID2 for creating new folder inside same directory.
I tried making a program
import os
path = 'C:\\Users\\Documents\\Python\\Projects'
for i in range (1,11):
os.chdir(path)
Newfolder= 'ID'+ str(i)
os.makedirs(Newfolder)
But this creates 10 folders at once but I want only one folder to be created when someone runs the script.
For every time script running to create a directory, you need a variable that must have to save. In your code, I think the loop is useless. I solved in this way for every time script running. Delete the generated .npy file from your directory, when you want to start from 1
import os
import numpy as np
path = 'define your directory'
f='Flag_variable.npy'
try:
Flag_variable = np.load('Flag_variable.npy')
Flag_variable = int(Flag_variable)
Flag_variable =Flag_variable+ 1
np.save(f,Flag_variable)
except FileNotFoundError:
np.save(f, 1)
Flag_variable=1
os.chdir(path)
Newfolder= 'ID'+ str(Flag_variable)
os.makedirs(path+Newfolder)
print('Total Folder created', Flag_variable)
for i in range (1,11):
pass
# os.chdir(path)
# Newfolder= 'ID'+ str(i)
# os.makedirs(path+Newfolder)
What you can do is use OS to search what folders are within the current dir, then take the highest number ID and create a new folder with that ID + 1.
import os
all_folders = os.listdir(path)
all_folders.sort()
latest = all_folders[-1].replace('ID', '')
new = int(latests) + 1
os.makedirs('ID'+str(latest))
I think you need to understand what the 'for' loop does.
It basically iterates the inside code as many times as you want or set to.
In your code, the for loop iterates 10 times.
That is the reason you get 10 folders created when you run your script once.
In your case, you want to remove the for loop and create just one folder. But, the important thing is that you want to know the number of folder you previously created so that the number in your next folder name follows the previous one.
In order to do that, you can read all the folders in your directory and get the latest one's name and parse it so you get the latest number. Then, increase the number by one and create the next folder.
How about this one.
if statement checks whether path candidate is already exists or not.
if path_cand is not exist, you can make directory and break for loop
import os
path = 'C:\\Users\\Documents\\Python\\Projects'
for i in range(1, 11):
path_cand = path + f"\\ID{i}"
if not os.path.exists(path_cand):
os.mkdir(path_cand)
break

How can I list the paths of all (sub)folders and put them separately in a list?

I have a program that generates many folders and files inside of them. In the main folder, i want the Code to look for all folders inside of it and save them separately in a list. So with self._list[0] I want to get one folderpath.
I am new to Python but I know already some path-printing lines but none of this give me the path. With this code I get the name of the folders, but I need additionally the path:
self._folderList=os.listdir(self._mainFolderPath)
you can attach the path manually to the folder name using this code:
self._folderList=[self._mainFolderPath + '\\' + folder_name for folder_name in os.listdir(self._mainFolderPath)]

Check if there are .format files in a directory

I have been trying to figure out for a while how to check if there are .pkl files in a given directory. I checked the website and I could find ways to find if there are files in the directory and list them, but I just want to check if they are there.
In my directory are a total of 7 .pkl files, as soon as I create one, the others are created so to check if the seven of them exist, it will be enough to check if one exists. Therefore, I would like to check if there is any .pkl file.
This is working if I do:
os.path.exists('folder1/folder2/filename.pkl')
But I had to write one of my file names. I would like to do so without searching for a specific file. I also tried
os.path.exists('folder1/folder2/*.pkl'),
but it is not working neither as I don't have any file named *.pkl.
You can use the python module glob (https://docs.python.org/3/library/glob.html)
Specifically, glob.glob('folder1/folder2/*.pkl') will return a list of all .pkl files in folder2.
You can use :
for dir_path, dir_names, file_names in os.walk(search_dir):
# Go over all files and folders
for file_name in file_names:
if (file_name.endswith(".pkl")):
# do something like break after the first one you find
Note : This can be used if you want to search entire directory with sub directories also
In case you want to search only one directory , you can run the "for" on os.listdir(path)

looping throught the folder

I need to solve trivial task running in loop sequence of the commands:
1) to take input .dcd file from the folder
2) to make some operations with the file
3) to save results in list
My code (which is not working !) looks like
# make LIST OF THE input DCD FILES
path="./inputs/"
dirs=os.listdir(path)
for traj in dirs:
trajectory = command(traj)
it correctly define name of the input but wrote that evvery file is empty
alternatively I've used below script to loop through the files using digit variable assidned to name of each file (which is not good in my current task because I need to keep name of each input file avoiding to use digits!)
# number of input files
n=3
for i in xrange (1,n+1):
trajectory = command('./inputs/file_%d.dcd' %(i))
In the last case all dcd files were correctly loaded (in opposit to the first example)! So the question what should I to fix in the first example?
os.listdir() gives you only the base filenames relative to the directory. No path is included.
Prefix your filenames with the path:
for traj in dirs:
trajectory = command(os.path.join(path, traj))

Categories

Resources