Find a given file recursively inside a directory - python-3.6

Find a given file recursively inside a dir. The code I tried is not showing any output, though I have a file C:\Users\anaveed\test\hoax\a.txt
Below the code
import glob
import os
os.chdir(r'C:\Users\anaveed\test')
for f in glob.iglob('a.txt', recursive=True):
print(f)
No output

Looks like you need.
import glob
for f in glob.iglob(r'C:\Users\anaveed\test\**\a.txt', recursive=True):
print(f)

This is another way of doing it:
import os
path = r'C:\Users\anaveed\test'
filename = 'a.txt'
for root, dirs, files in os.walk(path):
for name in files:
if name == filename:
print(os.path.join(root, name))
A couple of comments:
you do not need to use glob if you are not specifying wildcards, just use os.walk()
you do not need to move to a specific path to look for files therein, just save the path into a variable.
it would be even better to wrap this into a function (perhaps using a list comprehension).
the glob solution is typically faster.

Related

How to specify output name for qt5_add_translation?

I want to generate a plenty *.qm for plenty *.ts files for different languages using qt5_add_translation. All the *.ts files are named using *.de_DE.ts/*.fr_FR.ts/etc convention. But qt5_add_translation produce output, using only basename until first ., not the last one.
There is no possibility to pass options to lrelease using qt5_add_translation(QM_FILES "${PROJECT_NAME}.de_DE.ts" OPTIONS -qm "${PROJECT_NAME}.de_DE.qm") syntax.
Also setting OUTPUT_NAME property for source *.ts file is not working:
set_source_files_properties(
"${PROJECT_NAME}.de_DE.ts" PROPERTIES
OUTPUT_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}"
OUTPUT_NAME "${PROJECT_NAME}.de_DE.qm"
)
Producing filename in the case is still "${PROJECT_NAME}.qm", not "${PROJECT_NAME}.de_DE.qm"
How to override producing name for resulting *.qm file?
Surely I can make custom command and use it for my purposes, but I prefer to use ready qt5_add_translation.
EDIT:
Looking at /usr/local/Qt-5.9.2/lib/cmake/Qt5LinguistTools/Qt5LinguistToolsMacros.cmake I conclude, that there is no way to achieve desired using ready to use qt5_add_translation, because of using get_filename_component(qm ${_abs_FILE} NAME_WE) to get filename:
NAME_WE = File name without directory or longest extension
For my purposes there is need to use combination of ABSOLUTE (to get filename w/ full suffix), then to apply multiple times EXT in combination with NAME_WE to extract filename w/o shortest extension.
I ended up with the below custom function add_translation to replace qt5_add_translation:
function(ADD_TRANSLATION _qm_files)
foreach(_basename ${ARGN})
set(qm "${CMAKE_CURRENT_SOURCE_DIR}/${_basename}.qm")
add_custom_command(
OUTPUT "${qm}"
COMMAND "${Qt5_LRELEASE_EXECUTABLE}"
ARGS -markuntranslated "Not translated!" -nounfinished -removeidentical -compress "${CMAKE_CURRENT_SOURCE_DIR}/${_basename}.ts" -qm "${qm}"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${_basename}.ts" VERBATIM
)
list(APPEND ${_qm_files} "${qm}")
endforeach()
set(${_qm_files} ${${_qm_files}} PARENT_SCOPE)
endfunction()
It accepts basenames of *.ts files and produces list of resulting *.qm files: both in current source directory.
Please upgrade to Qt 5.9.4 or newer. The handling of .ts files with dots in the name has been fixed there, see also https://bugreports.qt.io/browse/QTBUG-64317 .

Absolute path of the project root directory in Julia

The project root directory of a file located in PROJECT_ROOT/lib/code.jl can be accessed with this code:
root = dirname(dirname(#__FILE__))
Using dirname() twice seems pretty ugly. Is there a better way to do this? With Ruby, I would use this code:
root = File.expand_path('../', File.dirname(__FILE__))
Thanks for making me find out about:
"/"*relpath((#__FILE__)*"/../..","/")
According to ?relpath, it gives a path from the location of the second argument in the file-system, to the first argument. Is this better than the double dirname solution?
A variant of the same niceness is:
normpath(joinpath(#__FILE__,"..",".."))
Closest to Ruby equivalent might be:
realpath(dirname(#__FILE__)*"/..")
I like to use
module Foo
const PROJECT_ROOT = pkgdir(Foo)
end # module
where the definition of PROJECT_ROOT can also be replaced by
const PROJECT_ROOT = dirname(dirname(pathof(Foo)))
Or, you could use
const PROJECT_ROOT = pkdir(#__MODULE__)
I just use
const PROJECT_ROOT = #__DIR__
from inside my _init.jl file, which resides in the project root directory (next to the src directory) and gives you a canonical path.
I get my _init.jl files automatically executed when opening a Julia session from inside that directories by having
isfile("_init.jl") && include(joinpath(pwd(), "_init.jl"))
in my ~/.julia/config/startup.jl file. If you started Julia elsewhere, you have to include("_init.jl") it (or respective relative path) manually.

Applying script in subfolders

I cd into a folder and start python. I want to apply a script to fix filenames in a directory and in sub folders.
import os
for dirname, subdirs, files in os.walk('.'):
os.rename(file, file.replace('\r', '').replace('\n', '').replace(' ', '_')
print 'Processed ' + file.replace('\r', '').replace('\n', '')
I get error "AttributeError: 'list" object has no attribute 'replace'. Help, please?
os.walk returns a 3-tuple that includes the root directory of the script, a list of subdirectories, and a list of files. You unpacked the 3-tuple in the for-loop and you're calling replace on the list of files.
You may want something like this:
for dirname, subdirs, files in os.walk('.'):
for file in files:
os.rename(file, file.replace('\r', '').replace('\n', '').replace(' ', '_')
print 'Processed ' + file.replace('\r', '').replace('\n', '')
You want to iterate through the list of the files and do you "replacing" on those individual files.

How to get file extension in Marklogic Server?

I want to get the file extension of uploaded file in Marklogic server. I know how to get the file name. But that gives filename plus extension like new.txt. But I want only extension not the full file name. How can I get just the file extension ?
There are many methods of getting file extensions from filename. For instance you can use functx:substring-after-last($filename, '.') or other methods (fn:substring-after) of getting substring after dot. Please see: xqueryfunctions.com
P.S. fn:tokenize($filename, '\.')[fn:last()]
I often use the following replace:
fn:replace("c:\a\b\c.d.e.txt", '^(.*\.)?([^\.]+)$', '$2')
But using functx is a good idea too, as suggested by Andrew. A copy of the functx library is distributed as part of the latter versions of MarkLogic. Just add the following import to get them available:
import module namespace functx = "http://www.functx.com" at "/MarkLogic/functx/functx-1.0-nodoc-2007-01.xqy";
HTH!
Just for variety, yet another expression that produces the extension :) :
reversed-string(substring-before(reversed-string($filePath), '.'))
where reversed-string($s) can be defined as:
codepoints-to-string(reverse(string-to-code-points($s)))
So the whole expression with the substitution is:
codepoints-to-string(
reverse(
string-to-codepoints(
substring-before(codepoints-to-string(reverse(string-to-codepoints($filePath))),
'.')
)
)
)

Easiest way to specify alternate transmogrifier _path?

I'm doing a content migration with collective.transmogrifier and I'm reading files off the file system with transmogrify.filesystem. Instead of importing the files "as is", I'd like to import them to a sub directory in Plone. What is the easiest way to modify the _path?
For example, if the following exists:
/var/www/html/bar/index.html
I'd like to import to:
/Plone/foo/bar/index.html
In other words, import the contents of "baz" to a subdirectory "foo". I see two options:
Use some blueprint in collective.transmogrifier to mangle _path.
Write some blueprint to mangle _path.
Am I missing anything easier?
Use the standard inserter blueprint to generate the paths; it accepts python expressions and can replace keys in-place:
[manglepath]
blueprint = collective.transmogrifier.sections.inserter
key = string:_path
value = python:item['_path'].replace('/var/www/html', '/Plone/foo')
This thus takes the output of the value python expression (which uses the item _path and stores it back under the same key.

Resources