-1

For several subdirectories I want to read a filename that is always starting with "_" into a variable. This filename is used as input for a function.

Not finding any solution to this problem atm.

paul
  • 1
  • 2

2 Answers2

0
dirContent = (os.listdir("."))
for i in dirContent:
    if os.path.isfile(i) and i.startswith("_"):
         variable = i

This code give you the file in a dir You can just call it recursively for all dirs in sub dir.

fexkoser
  • 13
  • 2
0

Here is an illustration of reading a file name into a Python variable:

filename = input("Enter a file name: ")

with open(filename, 'r') as f:
    contents = f.read()
    print(contents)

This code prompts the user to enter a file name and then stores the file name in the variable filename. The open() function is then used to open the file, and the file object is stored in the variable f. The with open statement is used to open the file and f.read() method is used to read the contents of the file. The contents of the file are then stored in the variable contents and printed to the console.

Another example:

import os

filename = os.path.join("path", "to", "file.txt")
with open(filename, 'r') as f:
    contents = f.read()
    print(contents)

This code uses the os.path.join() function to construct the file path and filename, and then uses the open() function to open the file, read its contents, and store them in the variable contents.

Please take note that the files in these examples are assumed to exist, be accessible, and have read permissions.

Here's an illustration of how you may utilize a file name that begins with "_" as input for a Python function by reading it from various subdirectories:

import os

def my_function(filepath):
    with open(filepath, 'r') as f:
        contents = f.read()
        print(contents)

root_dir = "path/to/root/directory"

for subdir, dirs, files in os.walk(root_dir):
    for file in files:
        if file.startswith("_"):
            filepath = os.path.join(subdir, file)
            my_function(filepath)

The os.walk() function is used to traverse the directory tree starting from the root_dir. For each subdirectory, it returns the subdirectory path, a list of subdirectories in the subdirectory, and a list of files in the subdirectory. The for loop iterates through the files, and the if statement checks if the file name starts with "_". If it does, the file path is constructed using the os.path.join() function, and passed as an argument to the my_function().

In the function my_function(filepath), The open() function is used to open the file and the f.read() method is used to read the contents of the file and store it into the variable contents. The contents of the file are then printed to the console.

Please note that this code requires the existence and accessibility of the root dir, the files within it, and the subdirectories. It also assumes that you have read access to all of the files.