Path, strings, and lines

Ian Kelly ian.g.kelly at gmail.com
Fri Jun 12 16:30:34 EDT 2015


On Fri, Jun 12, 2015 at 1:39 PM, Malik Rumi <malik.a.rumi at gmail.com> wrote:
>  I am trying to find a list of strings in a directory of files. Here is my code:
>
> # -*- coding: utf-8 -*-
> import os
> import fileinput
>
> s2 = os.listdir('/home/malikarumi/Projects/P5/shortstories')

Note that the filenames that will be returned here are not fully
qualified: you'll just get filename.txt, not
/home/.../shortstories/filename.txt.

> for line in lines:
>      for item in fileinput.input(s2):

fileinput doesn't have the context of the directory that you listed
above, so it's just going to look in the current directory.

>          if line in item:
>             with open(line + '_list', 'a+') as l:
>                 l.append(filename(), filelineno(), line)

Although it's not the problem at hand, I think you'll find that you
need to qualify the filename() and filelineno() function calls with
the fileinput module.

> FileNotFoundError: [Errno 2] No such file or directory: 'THE LAND OF LOST TOYS~'

And here you can see that it's failing to find the file because it's
looking in the wrong directory. You can use the os.path.join function
to add the proper directory path to the filenames that you pass to
fileinput.

> I don't know what the tilde at the end of 'The Land of Lost Toys' is about.

The trailing ~ is a convention used by Emacs (and possibly other
editors) for files that it creates as backups.



More information about the Python-list mailing list