Problem while giving strings in os module - python-3.x

import os
def compute(path, fileExt):
if os.path.exists(path): # checks if the path entered by the user exists
print("The path exists")
for foldername, subfolder, filename in os.walk(path):
for file in filename:
if file.endswith(fileExt):
print(os.path.join(foldername, subfolder, *file))
else:
print("The path does not exist !")
This program is about printing the full path of all the files in the folder mentioned by the user ending by the extension also mentioned by the user.
When I run the program i get a error on line 10 stating that : TypeError: join() argument must be str or bytes, not 'list'. I checked the variable type of file by using type(file) and it return str.
Where wrong ??

You should double check the os.walk() documentation and look closely at the error message you are getting. Your error message indicates you are trying to combine a list and a string. You have verified that file is a string, but what about foldername and subfolder.
os.walk() returns three things, the current directory file name, a list of all subdirectories of the current directory, and a list of all files in the current directory. This tells us that foldername is also a string but subfolder is actually a list of strings which causes the error message you are seeing.
Additionally, all of the files returned by os.walk() are contained within the root directory, not within the subdirectories. Therefore to print the path of the file, you want to join the file name to the root file path.
Just focusing on the os.walk() portion of your question, the following will print the full path of all files with the given file extension:
import os
for foldername, subfolder, files in os.walk(top, topdown=False):
for file in files:
if file.endswith(fileExt):
print(os.path.join(foldername, file))

Related

WinError2 keeps popping up with this python 3.7.3 script to delete files in a file tree without having to scroll through them

I am REALLY (2 days) new to all of this. I am trying to delete a bunch of files in a folder in my external HD with a python 3.7.3 script but an error keeps popping up.
Firstly, this code works fine and finds the folders:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
#os.unlink(filename)
print(filename)
But then when I remove the print(filename) the remove the hash, the folders can't be deleted with the following error popping up:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
os.unlink(filename)
os.unlink(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'rootpractice.docx'
The 'rootpractice' doc is clearly recognised but won't be deleted.
Does anyone know how I can solve this? Any help for this total beginner is much appreciated.
os.unlink and similar other methods which require file paths expect either a link relative to current folder in which your script is running (which you can find out with os.getcwd() ), or the full path.
When you are iterating with os.walk, you are only passing the filename and not the full path. Try this:
import os
for folderName, subfolders, filenames in os.walk("D:\Practice"):
for filename in filenames:
if filename.endswith('practice.docx'):
full_path = os.path.join(folderName, filename)
print("About to delete the file: {}".format(full_path))
os.unlink(full_path)

Does the following program access a file in a subfolder of a folder?

using
import sys
folder = sys.argv[1]
for i in folder:
for file in i:
if file == "test.txt":
print (file)
would this access a file in the folder of a subfolder? For Example 1 main folder, with 20 subfolders, and each subfolder has 35 files. I want to pass the folder in commandline and access the first subfolder and the second file in it
Neither. This doesn't look at files or folders.
sys.argv[1] is just a string. i is the characters of that string. for file in i shouldn't work because you cannot iterate a character.
Maybe you want to glob or walk a directory instead?
Here's a short example using the os.walk method.
import os
import sys
input_path = sys.argv[1]
filters = ["test.txt"]
print(f"Searching input path '{input_path}' for matches in {filters}...")
for root, dirs, files in os.walk(input_path):
for file in files:
if file in filters:
print("Found a match!")
match_path = os.path.join(root, file)
print(f"The path is: {match_path}")
If the above file was named file_finder.py, and you wanted to search the directory my_folder, you would call python file_finder.py my_folder from the command line. Note that if my_folder is not in the same directory as file_finder.py, then you have to provide the full path.
No, this won't work, because folder will be a string, so you'll be iterating through the characters of the string. You could use the os module (e.g., the os.listdir() method). I don't know what exactly are you passing to the script, but probably it would be easiest by passing an absolute path. Look at some other methods in the module used for path manipulation.

Can`t use the files inside my subdirectories

I`m creating a program that can read certain data from some txt files, the problem comes when I try to use the files inside subdirectories (the subdirectories are inside the main directory of the program. I'm using a for the option to find all the files and then create a new file with the info that I found. The main problem is that I can't read those files.
I tried using a for a function that creates a list of directories, files and roots, this works fine, but in the moment of running the file it says "it cannot be found txt file". The if not condition is made so the program excludes all.DS_Store files. I think the problem could be the way I open the file but im not sure
for root, directories, filenames in os.walk("Files_to_Insert"):
if not (filenames[-1] == ".DS_Store"):
lastFile = filenames[-1]
print lastFile
with open (lastFile, 'rt') as myfile:
IOError: [Errno 2] No such file or directory: txt
The mistake happens in the with open because it can`t find the file.
When I print I get all the txt files, but I can,t use them in the "with open"
A typical os.walk I use goes like this:
import os
for root, directories, filenames in os.walk("."):
for f in filenames:
if f.endswith(".DS_Store"):
continue
print(os.path.abspath(f))
with open (os.path.abspath(f), 'rt') as myfile:
I solve it by giving the path and the text file in separate strings:
for root, directories, filenames in os.walk("Files_to_Insert"):
if not(filenames[-1] == ".DS_Store"):
lastFile = filenames[-1]
# print (lastFile)
with open(str(root) + '/' + lastFile,'rt') as myfile:

Loop through files in a directory for a particular file. If the file is not there, append a "File not found" to a list else append the file location

I have a list of file names in an excel sheet that I need the file location to. I want the code to run through all the files in the directory specified and if it finds the file, to append the file location to a list. If it doesn't find the file, I want it to append a "File not found" to the list.
I've got my code to work if the file does exist, however, I can't seem to find a way to solve the problem when the file doesn't exist. I've tried:
if name not in file:
file_location.append("File Not Found")
but what this does is append a "File Not Found" for each file it loops through.
def file_loc(basedir, filename):
"""Searches through the directory for a particular file and then saves that path into a list"""
for root, dirs, files in os.walk(basedir):
for name in files:
if filename in name:
location = os.path.abspath(os.path.join(root, name))
file_location.append(location)
I would like a list that prints out all the file locations of the files in a list and if a file location cannot be found, the list should contain a "File Not Found". So for example, if the files I wanted to search for were [foo, bar, soap] and the soap file was not in my directory it would print out:
[File/path/to/foo, File/path/to/bar, "File Not Found"]
Any help would be much appreciated!
The issue is you are checking whether a particular file name matches, and you want to know if any matched. If after you have run through all the files none matched, then you can say it was not found. So I would suggest using a boolean variable to see if it was found at all. Then after the loop is complete check and append if necessary. It should look something like this.
def file_loc(basedir, filename):
"""Searches through the directory for a particular file and then saves that path into a list"""
found = false
for root, dirs, files in os.walk(basedir):
for name in files:
if filename in name:
location = os.path.abspath(os.path.join(root, name))
file_location.append(location)
found = True
if not found:
file_location.append("File Not Found")

create a list of files to be deleted

I am working on a search-and-destroy type program which I need it to do is search all directories with a certain file-name and append them to a list. after that delete all those files...not objects in list or the list...
import os
file_list=[]
for root, dirs, files in os.walk(path-to-dir'):
for f_name in files:
if f_name.startswith("file-name"):
file_list.append(f_name)
I could write up to appending part of the code but I don't know next...
Some help please
To remove a file from your computer, use os.remove(). It takes full path to the file as it's parameter, so instead of calling os.remove("infectedFile.dll") you would call os.remove("C:/program files/avira/infectedFile.dll")
So your file_list should contain full paths to the files, and then just call:
for file in file_list:
os.remove(file)
Modify your file_list.append(f_name). The f_name is only a bare name. You need to add the path to the file name in the time of processing, because you do not know where the file was found in the directory hierarchy:
file_list.append(os.path.join(root, f_name))
The root variable contains the path during walking.
To make check whether your code works, just print the content of the list:
print('\n'.join(file_list))
Or you can do it in the loop to get ready for the later part:
for fname in file_list:
print(fname)
Then you just add the os.remove(fname) to remove the file name:
for fname in file_list:
print('removing', fname)
os.remove(fname)

Resources