On 2015-06-13 05:48, Malik Rumi wrote:
On Friday, June 12, 2015 at 3:31:36 PM UTC-5, Ian wrote:
On Fri, Jun 12, 2015 at 1:39 PM, Malik Rumi 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.


Yes, that is what I want.

> 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.

Can you explain a little more what you mean by fileinput lacking the context of 
s4?

listdir returns the names of the files that are in the folder, not
their paths.

If you give fileinput only the names of the files, it'll assume they're
in the current folder (directory), which they (probably) aren't. You
need to give fileinput the complete _paths_ of the files, not just
their names.


>          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.

By 'qualify', do you mean something like
l.append(fileinput.filename())?


> 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 tried new code:

# -*- coding: utf-8 -*-
import os
import fileinput


os.join _returns its result.

os.path.join('/Projects/Pipeline/4 Transforms', '/Projects/P5/shortstories/')
s2 = os.listdir('/Projects/P5/shortstories/')

At this point, s2 contains a list of _names_.

You pass those names to fileinput.input, but where are they? In which
folder? It assumes they're in the current folder (directory), but
they're not!

for item in fileinput.input(s2):
      if 'penelope' in item:
         print(item)

But still got the same errors even though the assignment of the path variable 
seems to have worked:

[snip]

Try this:

    filenames = os.listdir('/Projects/P5/shortstories/')
    paths = [os.join('/Projects/P5/shortstories/', name) for name in names]
    for item in fileinput.input(paths):

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to