Raghavendra
Raghavendra

Reputation: 583

os.walk() is not throwing any error nor the result in python

I am trying to print the file names which are in a predefined paths where the paths are stored in paths.txt. But when I execute the below code, I'm not getting any error nor the files names printed.

import os
with open('D:\paths.txt', 'r') as file:
    data = file.read()
    path = data.split(";")
    print(path)
    for line in path:
        for root, dirs, files in os.walk(line):
            for name in files:
                print(name)

Example of paths.txt

Upvotes: -1

Views: 700

Answers (1)

Peter Emil
Peter Emil

Reputation: 603

You need to remove the double-quotes from the file (""). Here is why; When the file gets read by Python, after it does the .split(), the double-quote characters are part of the Python string. So instead of passing into os.walk() the path D:\bp1, you were actually passing in "D:\bp1", and there was no path that starts with a " that's why nothing was happening.

You would only need to provide the double quotes if you're writing the name in a terminal/command prompt and don't want to escape the double quotes, or if you're trying to define the string inside Python using the double quote literal, for example path = "D:\\bp1" (notice that in that case you also have to escape the \ with another one.

Upvotes: 1

Related Questions