I don't understand the 'from' in Python [duplicate] - python

This question already has answers here:
Use 'import module' or 'from module import'?
(23 answers)
`from ... import` vs `import .` [duplicate]
(6 answers)
Closed 2 years ago.
from glob import glob
from os.path import isfile
def countwords(fp):
with open(fp) as fh:
return len(fh.read().split())
print "There are" ,sum(map(countwords, filter(isfile, glob("*.txt") ) ) ), "words in the files."
in the first line, why don't this just simply import glob library?
Is there any reason for using "from glob" in front of "import glob"?

If you write import glob, you would need to use glob.glob.
from glob import glob takes glob.glob and makes it available as just glob.

>>> import glob
>>> dir(glob)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
'fnmatch', 'glob', 'glob0', 'glob1', 'has_magic', 'iglob', 'magic_check',
'os', 're', 'sys']
You can see all of the functions in the glob module here, you may for example want an iterator version of glob and in that case you would use:
from glob import iglob

if you use import glob, for the function glob("*.txt"), you have to write glob.glob("*.txt").
basically, the first glob in the from glob import glob is the name of the module, while the second one is the name of the function.

from glob import glob will import glob attribute of glob module when import glob will import whole module

This link seemed to explain all of the different variations quite well:
http://effbot.org/zone/import-confusion.htm
The bottom line is that importing a specific thing from a module gives you a direct reference to ONLY that thing and not the whole module.

When you have import glob, you import all the functions from that module. When you have from xyz import abc, you're only importing the abc function from the xyz module. In this case, you're importing the glob function from the glob module.
This way, in the Python code, if you want to use the glob function, instead of writing glob.glob, you only have to write glob.

Related

Glob and pathlib Path.glob yield different results for same pattern [duplicate]

The the new Path.glob from pathlib seems to behave differently from the old glob.glob when the glob pattern ends in a slash it seems.
In [1]: from pathlib import Path
In [2]: from glob import glob
In [3]: glob('webroot/*/')
Out[3]: ['webroot/2017-06-07/']
In [4]: list(Path().glob('webroot/*/'))
Out[4]:
[PosixPath('webroot/.keep'),
PosixPath('webroot/2017-06-07'),
PosixPath('webroot/matches.2017-06-07.json')]
Is that by design, some compatibility issue I haven’t encountered? And is there a way to stop it from doing that?
For now I’ll work around it with:
[path for path in Path().glob('webroot/*/') if path.is_dir()]
There's an open bug about this:
https://bugs.python.org/issue22276
No resolution yet.
Your workaround looks fine, although if you don't mind also including the 'webroot' directory itself you may prefer using a ** glob:
>>> list(Path('webroot').glob('**'))
[PosixPath('webroot'), PosixPath('webroot/2017-06-07')]

How to print to the path of the file in python using glob [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 3 years ago.
I want to find the file name and then print the path of that file using python. My program runs successfully as follows.
from pathlib import Path
import glob
import os
for file in Path('<dir_address>').glob('**/*some_string*.*fastq.gz'):
print(file)
It print the paths of all the files having some_string matching in its name in the .
Now I want to define an argument in place of some_string as follows.
file_name="abc"
from pathlib import Path
import glob
import os
for file in Path('<dir_address>').glob('**/*file_name*.*fastq.gz'):
print(file)
It doesn't give any output. My questions is how to give this sub_string as a variable in a program which will bring the files path of all the files having this specific sub_string in their name.
I think this is what you need:
from pathlib import Path
import glob
import os
file_name="abc"
for file in Path('<dir_address>').glob(f'**/*{file_name}*.*fastq.gz'):
print(file)
In the f-string {filename} gets replaced by the string of the variable filename.

Failing to import a file

I am currently trying to code a searching program, which makes use of a program I've already written. It refuses to get to the second print statement.
print("Relevance: ")
# import sqlite3
import Breakdown.py as bd
import re, nltk
from nltk.corpus import wordnet
# from sqlite3 import Error
from autocorrect import spell
print("Input line: ")
The file structure looks like this:
However, I can't work out why it can't get past that import section.
This is somewhat important.
Thanks.
Just write:
import Breakdown as bd
python will import the Breakdown.py file as a module. It will be looking for any variable or function named "py" in the Breakdown module if you use:
import Breakdown.py as bd
... which I don't think is the case here.
You should put the Breakdown.py file in the path where you're starting Python or in one of the directories where Python looks for libraries:
import os
for p in sys.path:
print(p)
and use import Breakdown (no .py).
Or else add to sys.paththe folder where the module is with:
sys.path.append('/your/foldername')

Rename a folder with source folder name matched by wildcard ("*")

I have a local folder named "abcd-1" and I want to do something like this:
import os
os.rename("abcd*", "abcd")
I know there's only one such folder so it's a valid operation, but it doesn't look like os.rename supports *. How can I solve it?
See glob
>>> import os, glob
>>> for f in glob.glob("abcd*"):
... os.rename(f, "abcd")
...
>>>
Check if there is only one result or use glob.glob("abcd*")[0] for first result.
Use os.path.isdir() to check whether it is a directory
You can use a combination of glob , os.path.isdir() function (to determine if it is a directory) , and then os.rename() to rename the actual file.
Example -
import glob
import os
import os.path
lst = glob.glob("abcd")
for element in lst:
if os.path.isdir(element):
os.rename(element,"abcd")
Use the glob module
eg
glob.glob("abcd*")
will return ["abcd-1"]
then you can rename the folder
You should probably use an assert statement to make sure theres only 1 result

How to find files with specific case-insensitive extension names in Python [duplicate]

This question already has answers here:
Ignore case in glob() on Linux
(9 answers)
Closed 9 years ago.
glob.glob() is case-sensitive.
Is there any simple way to find files with specific case-insensitive extension names in Python.
The fnmatch module provides more control over pattern matching than the glob module:
>>> import os
>>> from fnmatch import filter
>>> filter(os.listdir('.'), '*.[Pp][Yy]')
You can also use os.listdir() followed by a regular expression match:
>>> import os, re
>>> [filename for filename in os.listdir('.')
if re.search(r'\.py$', filename, re.IGNORECASE)]
This should do the trick:
import os
import glob
def find_case_insensitve(dirname, extensions):
for filename in glob.glob(dirname):
base, ext = os.path.splitext(filename)
if ext.lower() in extensions:
print filename
find_case_insensitve('/home/anthon/Desktop/*', ['.jpeg', '.png', '.jpg'])
Don't forget to specify the list of extensions in lowercase.

Categories

Resources