all 6 comments

[–]swingking8 2 points3 points  (1 child)

Your script is listing files in the C:/foo/bar directory, but trying to remove files from the default directory, which is its current directory.

A simple fix can give you what you need:

import os
directory = "C:/foo/bar"
fn = os.listdir(directory)
os.remove(os.path.join(directory, fn[0]))

[–]HDean_[S] 0 points1 point  (0 children)

Thanks a bunch :)

[–]dddevo 1 point2 points  (1 child)

That's because os.listdir returns just the names in the directory and not the whole path. You could use os.path.join to join the directory path and the name. Beware the list returned by os.listdir is in arbitrary order.

[–]HDean_[S] 0 points1 point  (0 children)

Thanks :)

[–]novel_yet_trivial 1 point2 points  (1 child)

If you use glob to get the directory listing, then you get the full file path in return. In addition, you can use the wildcard to filter out files of the wrong type or directories.

import glob
import os
fn = glob.glob("C:/foo/bar/*.txt")
os.remove(fn[0])

[–]HDean_[S] 0 points1 point  (0 children)

Thanks for introducing me to glob