-1

Can anyone tell me why I get this error? The file is in the folder.

import os

with open("C:\\Users\\42077\\Desktop\\test\\vystup\\!output.txt", "a")as f:
    for root, dirs, files in os.walk("C:\\Users\\42077\\Desktop\\test\\"):
        for path in files:
            if path.endswith(".txt"):
                with open(path, 'r') as file:
                    data = file.readlines()
                    f.write("{0} {1}\n".format(data[2], path))
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 2
    [Need the path for particular files using os.walk()](https://stackoverflow.com/a/16465439) – 001 Feb 21 '21 at 22:20

1 Answers1

0

the files os.walk() returns is not a list of paths to files it's a list of names (as strings) of files in the directory where os.walk() is currently looking (root).

for path in files:
    if path.endswith(".txt"):
        with open(path, 'r') as file:

so at the end here open() is given a file name like example.txt. And when open() is not given an absolute path it looks from the current working directory. Meaning it tries to find this file wherever this python file is located, and promptly gives an error.

Dexus
  • 45
  • 1
  • 6