How do I list files and directories those are not hidden in current directory using crystal language? - crystal-lang

I wrote my own minimal version of "ls" command (Linux) using crystal language and here is my code:
require "dir"
require "file"
def main()
pwd = Dir.current
list_dir = Dir.children(pwd)
puts("[+] location: #{pwd}")
puts("------------------------------------------")
list_dir.each do |line|
check = File.file?(line)
if check == true
puts("[+] file : #{line}")
elsif check == false
puts("[+] directory: #{line}")
else
puts("[+] unknown : #{line}")
end
end
end
main
It works but it also listing all hidden files and directories (.files & .directories) too and I do not want to show those. I want the result more like "ls -l" command's result not like "ls -la".
So, what I need to implement to stop showing hidden files and directories?

There is nothing special about "hidden" files. It's just a convention to hide file names starting with a dot in some contexts by default. Dir.children does not follow that convention and expects the user to apply approriate filtering.
The recommended way to check if a file name starts with a dot is file_name.starts_with?(".").

Related

I am writing a DXL script to print a modulename with path using a function . I need to remove if the directory has remote in that path

Below module is forming a directory from a path
Checkmodules("Cus", "projectname".cfg", ".*(Cus|Cer Requirements|Cer Speci|ASM|/ASM24e|Specs).*");
The above line forms below folder directory, so I need to modify it when the directory has remote in the path its should be removed entire directory.
Output path
Cus/spec/cer/
cus/val_remote/value - this also needs to be removed
Cus/sys/remote ---- to be removed entire path
You can do a replace (to an empty string) with the following regex combined with the flag g (global=all occurrences) and m (multiline)
^.*remote.*$
In JavaScript this would be :
outputPath.replace(/^.*remote.*$/gm, '')

Django not recognizing files deleted/added

I have the following function that gives me the list of files(complete path) in a given list of directories:
from os import walk
from os.path import join
# Returns a list of all the files in the list of directories passed
def get_files(directories = get_template_directories()):
files = []
for directory in directories:
for dir, dirnames, filenames in walk(directory):
for filename in filenames:
file_name = join(dir, filename)
files.append(file_name)
return files
I'am adding some files to the template directories in Django. But this function always return the same list of files even though some are added/deleted in the run time. These changes are reflected only when I do a server restart. Is that because of some caching that os.walk() performs or is it required that we need to restart the server after adding/removing some files ?
It is not django problem, your behaviour is result of python interpreter specific:
Default arguments may be provided as plain values or as the result of a function call, but this latter technique need a very big warning. Default values evaluated once at start application and never else.
I' m sure this code will solve your problem:
def get_files(directories = None):
if not directories:
directories = get_template_directories()
files = []
for directory in directories:
for dir, dirnames, filenames in walk(directory):
for filename in filenames:
file_name = join(dir, filename)
files.append(file_name)
return files
You can find same questions on Stackoverflow Default Values for function parameters in Python

listing directories having "-" character in directories name

I want to list the directories in current directory having "-" character in directories name. I used os.listdir(path). Its giving me error :
"WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect:"
Any help will be greatly appreciated
Use os.listdir to get directory contents and then filter using os.path.isdir to check if each item is a dir:
dirs_with_hyphen = []
for thing in os.listdir(os.getcwd()):
if os.path.isdir(thing) and '-' in thing:
dirs_with_hyphen.append(thing)
print dirs_with_hyphen # or return, etc.
And that can be shortened using list comprehension:
dirs_with_hyphen = [thing for thing in os.listdir(os.getcwd()) if os.path.isdir(thing) and '-' in thing]
I'm using os.getcwd but you could pass in any string that represents a folder.
If you're getting an error about the filename being incorrect, you're probably not escaping correctly or it's not pointing to the right folder (absolute vs relative path issue).
I did some testing and I managed to get your error. I don't know if this is what you did to get the error though since no example has been provided.
What I did though is give an invalid drive path. Not one that could be valid and doesn't exist, one that is always wrong eg.'C::\' or 'CC:\' just anything that's not 'C:\'. As for your question.
Path should generally look like this, prefixing with r to ignore backslash as escape character or double backslash.
import os
path = r"C:\Users\Steven\Documents\"
path = "C:\\Users\\Steven\\Documents\"
for file in os.listdir(path):
if os.path.isdir(path+file) and '-' in file:
print path + file
#List Comp
[path+file for file in os.listdir(path) if os.path.isdir(path+file) and '-' in file]

How to get a file to be used as input of the program that ends with special character in python

I have an output file from a code which its name will ends to "_x.txt" and I want to connect two codes which second code will use this file as an input and will add more data into it. Finally, it will ends into "blabla_x_f.txt"
I am trying to work it out as below, but seems it is not correct and I could not solve it. Please help:
inf = str(raw_input(*+"_x.txt"))
with open(inf+'_x.txt') as fin, open(inf+'_x_f.txt','w') as fout:
....(other operations)
The main problem is that the "blabla" part of the file could change to any thing every time and will be random strings, so the code needs to be flexible and just search for whatever ends with "_x.txt".
Have a look at Python's glob module:
import glob
files = glob.glob('*_x.txt')
gives you a list of all files ending in _x.txt. Continue with
for path in files:
newpath = path[:-4] + '_f.txt'
with open(path) as in:
with open(newpath, 'w') as out:
# do something

How do I deal with output files when using argparse?

I have a program and I want to make it so that if the user specifies the exact name of the 2 output files given, then those files will be named at the user's preference.
For ex:
-o file1.txt file2.txt
If the output files aren't specified then the script will automatically generate the files with default names.
You can use the argparse module, which provides clean ways of handling input arguments. For your task, you can use something like
arguments = argparse.ArgumentParser()
arguments.add_argument('fileNames', nargs='*', help='Output file names', default = ['val1', 'val2'])
inputArgs = arguments.parse_args()
# User may decide to give just one file name
outFileName1 = inputArgs.fileNames[0]
outFileName2 = 'val2' if len(inputArgs.fileNames) == 1 else inputArgs.fileNames[1]