I'm using the following code to iterate through an xml file, I want to extract the folder structure.
Ideally I'd like a list in which each element would have the following structure:
top_folder, first_folder, page_view
Alternatively a dictionary with top_folder and page_view would also work for me.
The problem I'm having is that if I try to print the variable from the previous for loop, it doesn't work. Which I don't understand, as I'm use it in other parts of the script.
The code is:
top = ""
for first_iter in root_navigation:
for second_iter in first_iter:
for top_folder in second_iter:
if top_folder.text and top_folder.text.strip():
#print top_folder.text
top == top_folder.text
for first_folder in top_folder:
if first_folder.text and first_folder.text.strip():
#print " "+first_folder.text
first = first_folder.text
for page_view in first_folder:
if page_view.text and page_view.text.strip():
#print " "+page_view.text
print top+":"+first+":"+page_view.text
So far I've tried the above code, and directly printing the top_folder.text and first_folder.text in the last if.
The only output I manage to get, the commented prints is something like:
Top Folder
First Folder
Page View
First Folder
Page View
.....
Which doesn't really work as I'd like to have a list or something I could match later with the view name and get the top folder for it.
Any ideas of why the variables are not getting across the for loops or another way I could do this?
Thanks in advance :-)
Related
I am using os.scandir to get a list a files in a given directory. It works fine by returning the files names. I am wondering if there is a way to point to a file list generated by scandir. In fact I am looking for a index like listbox so you can process a choice made by a user. Thanks for any help. The code I have is like this:
def listFiles():
dir_entries = scandir(instaPath)
for entry in dir_entries:
if entry.is_file():
info = entry.stat()
print(entry.name)
# print(entry.index ?)
New to Python, an interesting problem I encountered and trying to solve the zip file to identify the top level directory using folders. I do not know how to put words together to make sense. I will write up a pseudo-code to give you the feel of it.
for folders in Zipfile.namelist():
if /zipfile/1folder1/:
return PASS
elif:
/zipfile/1folder1/
/zipfile/1folder2/
/zipfile/1folder1/2folder1/
return FAIL
I am interested in reading the folder names, not file names. I tried the reduce() method but to no avail because it will go all the way to the lowest level folder which I do not want. I want only the top level, or the first, folder as in /zipfile/1folder1/. It has to be only and one folder, not multiple folders at the top level directory.
I cannot figure out a method to read the folder and create a for loop iteration to retrieve the index value to determine the number of folders at top level directory.
Thanks!
I found the workaround to it. It was the os.sep including .split and .keys methods that did the trick and performed the iteration.
for folders in Zipfile.namelist()[1:]:
seps = len(folders.split(os.sep))
if seps > 2:
if seps not in dir_count.keys():
count[seps] = 0
count += 1
if count[seps] > 1:
raise exception
I have 2 .py files. Let's name them foo.py and list.py
list.py is not having any code but just a list which looks like this: allowed = ['a', 'b', 'c']
This is all the list.py contains...
Now, the foo.py has a code which basically uses the list inside the list.py to only allow certain inputs (which should be in the list, else: pass)
I added a code to be able to add elements to the list from inside the program, but i'm unable to do so. I have tried to use the append() function. This brings no change to the list...
Please help me edit and write changes to the list inside list.py by providing the right code to so.
Thanks.
What is likely happening is you are sending a copy of the list, when your program is running - and then appending to that list - without impacting the initial list in list.py
I would look at making sure that when you instantiate the original list in list.py, you aren't doing so in such a way that means each time that code block is called, the list is defined again as you call that code block or function again.
If you are trying to use a program in foo.py to explicitly edit the list.py file, you are probably as well off to simply use python's pickle module, which saves the state of python objects to file, and you would then be able to load them as normal later, for example:
try:
with open(list, 'r') as file:
yourlist = pickle.load(file)
except(FileNotFoundError):
yourlist = ['someDefaultValue','anotherDefaultValue']
# Your code block, doing whatever you're doing
with open(list, 'w') as file:
pickle.dump(yourlist, file)
Without knowing more about what you're looking at or exactly what you're trying to do - it's hard to give a better answer!
I've seen a lot of people asking questions about searching through folders and creating a list of files, but I haven't found anything that has helped me do the opposite.
I have a csv file with a list of files and their extensions (xxx0.laz, xxx1.laz, xxx2.laz, etc). I need to read through this list and then search through a folder for those files. Then I need to move those files to another folder.
So far, I've taken the csv and created a list. At first I was having trouble with the list. Each line had a "\n" at the end, so I removed those. From the only other example I've found... [How do I find and move certain files based on a list in excel?. So I created a set from the list. However, I'm not really sure why or if I need it.
So here's what I have:
id = open('file.csv','r')
list = list(id)
list_final = ''.join([item.rstrip('\n') for item in list])
unique_identifiers = set(list_final)
os.chdir(r'working_dir') # I set this as the folder to look through
destination_folder = 'folder_loc' # Folder to move files to
for identifier in unique_identifiers:
for filename in glob.glob('%s_*' % identifier)"
shutil.move(filename, destination_folder)
I've been wondering about this ('%s_*' % identifier) with the glob function. I haven't found any examples with this, perhaps that needs to be changed?
When I do all that, I don't get anything. No errors and no actual files moved...
Perhaps I'm going about this the wrong way, but that is the only thing I've found so far anywhere.
its really not hard:
for fname in open("my_file.csv").read().split(","):
shutil.move(fname.strip(),dest_dir)
you dont need a whole lot of things ...
also if you just want all the *.laz files in a source directory you dont need a csv at all ...
for fname in glob.glob(os.path.join(src_dir,"*.laz")):
shutil.move(fname,dest_dir)
I want to make a name list and store all the names in four folders. I build
namelist = {1:[], 2:[], 3:[], 4:[]}
In the method, I write
for file_name in sorted(os.listdir(full_subdir_name)):
full_file_name = os.path.join(full_subdir_name,file_name)
#namelist[level] += blabla...
I want to add the names from the first folder into namelist[1], from the second folder to namelist[2]. I don't know how I can add all the names in different levels to it. Thx!
I am not totally sure this is what you are getting at with your question above. But it seems that first, you want to use enumerate() to allow you to keep the index and name of the four folders. But then, I think you will actually need an additional for-loop, based on your comments above, to actually append all of the contents for each of the files within each sub-folder. The following should do the trick.
Also note that your dictionary keys start with 1, so you need to account for the fact that the enumerate index starts with 0.
# Here, enumerate gives back the index and element.
for i,file_name in enumerate(sorted(os.listdir(full_subdir_name))):
full_file_name = os.path.join(full_subdir_name,file_name)
# Here, 'elem' will be the strings naming the actual
# files inside of the folders.
for elem in sorted(os.listdir(full_file_name)):
# Here I am assuming you don't want to append the full path,
# but you can easily change what to append by adding the
# whole current file path: os.path.join(full_file_name, elem)
namelist[i+1].append(elem)