Search code examples
pythonpython-3.xstring-concatenation

How do I concatenate the folder and the file name with a forward slash?


from pathlib import Path
import os

folderpath = input("What is the absolute path to Superman's folder?")

mypath = Path(folderpath)

mypath = os.listdir(folderpath)
for files in mypath:
    print ("Found one of Superman's's files..." + files)
#up to here, the code is good

for read in byfiles:
    byfiles = ('mypath\\files')
    byfiles.read_text()
    if "Superman" in read:
        print("Found Superman in file " + read)

I need to search the files in input path and locate the word Superman and then print the location where the word was found. I cannot get the concatenation to work along with the .read_text().

This is the output:

What is the absolute path to Superman's folder?C:\Users\OneDrive\Documents\Superman_files
Found one of Superman's files...boring_document.txt
Found one of Superman's files...eggs.txt
Found one of Superman's files...hello.txt
Found one of Superman's files...secret_document.txt
Found one of Superman's files...spam.txt

Any help would be greatly appreciated.


Solution

  • os.listdir returns a list of strings so you can check like:

    for read in mypath:
        if "Superman" in read:
            print("Found Superman in file " + read)
    

    if you want to check the content of your file you can use:

    from pathlib import Path
    
    
    folderpath = input("What is the absolute path to Superman's folder?")
    mypath = Path(folderpath)
    
    for child in mypath.iterdir():
        if child.is_file():
            with open(child, 'r') as file:
                if "Superman" in file.read():
                    print("Found Superman in file ",  child.relative_to(mypath))