-1

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

Unknownzdx
  • 179
  • 2
  • 14
  • Any command line arguments passed through the command line and accessed with `sys.argv` will be *strings*. Take a look at the `os.walk` documenation and examples. https://docs.python.org/3/library/os.html#os.walk – SyntaxVoid Sep 16 '19 at 17:09
  • @SyntaxVoid The problem is I don't know the entire path. So I know the path to the main folder however I need to take the subfolders as inputs and access the files in each subfolder. The solutions to your link don't seem to be working for me – Unknownzdx Sep 16 '19 at 17:44
  • If you don't know the entire path, then which folder are you trying to search? One relative to the running script? – OneCricketeer Sep 16 '19 at 18:07
  • I figured it out now, so basically I have to take an input of folders and iterate through them, I won't necessarily know the name of the folders so figuring out the path would be difficult – Unknownzdx Sep 16 '19 at 20:25

3 Answers3

1

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?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

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.

gstukelj
  • 2,291
  • 1
  • 7
  • 20
0

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.

SyntaxVoid
  • 2,501
  • 2
  • 15
  • 23