I want to check if a directory exists, if not create it.
How can I achieve this? I tried writeFile since I wanted to create a file in it, but that doesn't seem to work.
existsDir: http://nim-lang.org/docs/os.html#existsDir,string
createDir: http://nim-lang.org/docs/os.html#createDir,string
So this should work:
import os
let dir = "foo"
if not existsDir(dir):
createDir(dir)
Related
I have a file structure as following:
/home/myhome/me/staging/15/1234/my_stats/
/home/myhome/me/staging/16/5678/my_stats/
/home/myhome/me/staging/17/7890/my_stats/
/home/myhome/me/staging/18/3456/my_stats/
I need to travel to the dir "my_stats" and execute query to find files in my cmd. There are multiple dirs in "staging" and I need to go into every one of them and check if 'my_stats' dir exists. If it exists, then I need to run a cmd query in "my_stats" dir.
The dir structure will always be in the following format:
/home/myhome/me/staging/<2 digit name>/<4 digit name>/my_stats/
I have tried iterating through the structure using a nested for loop and checking all dirs in 'staging' which is proving to be slow. Is there a way to using the 'find' command with 'depth' to do the same?
Or can we implement this with pattern matching ?
Appreciate the help. Thanks!
found the answer!
we can use * for it.
/home/myhome/me/staging/*/**/my_stats/*
Will try to find a better solution which can maybe use len of dir to better differentiate it
Try this one
find . -type f -path "./[0-9][0-9]/[0-9][0-9][0-9][0-9]/my_stats/*"
can replace the . with your own path.
I am trying to read through a file using the with open () function from python. I hand in the filepath via a base path and then a relative path adding on it:
filepath = base_path + path_to_specific_file
with open (filepath) as l:
do_stuff()
base_path is using the linux home symbol ( I am using Ubuntu on a VM) ~/base_path/ since I want to have the filepath adapted on every device instead of hardcoding it.
This does not work. When I execute the code, it throws a file not found error, although the path exists. I even can open it by clicking the path in the vscode terminal.
According to this thread:
File not found from Python although file exists
the problem is the ~/ instead of /home/username/. Is there a way to replace this to have it working on every device with the correct path? I cannot comment yet on this thread since I do not have enough reputation, therefore I needed to create this new question. Sorry about that.
You can use the expanduser() from pathlib for this. Example
import pathlib
filepath = pathlib.Path(base_path) / path_to_specific_file
filepath = filepath.expanduser() # expand ~
with open(filepath) as l:
do_stuff()
This should work fine.
You can join paths e.g. with:
filepath = '/'.join((basepath, path_to_specific_file))
Or do as Kris suggested: use pathlib:
>>> basepath = Path('/tmp/')
>>> path_to_specific_file = Path('test')
>>> filepath = basepath / path_to_specific_file
>>> print(filepath)
/tmp/test
EDIT:
To access $HOME (~) you can use Path.home().
I'm in the process of porting a makefile project to scons and I can't figure out how to create a unique #define for each file. I would like to have the base filename for each file defined in order to support some custom debug macros. In the makefile, I'm able to do this with the following definition.
-DBASE_FILE_NAME=\"$(<F)\"
I'm not sure how to do this or if it is even possible in scons and would appreciate any feedback.
After some experimentation, the following seems to work.
import os
from glob import glob
# use Python glob, not scons Glob!
CPP_FILES = glob('./src/*.cpp')
env = Environment(CPPPATH='./include', etc...)
for f in CPP_FILES:
env.Object(f, CPPDEFINES={'BASE_FILENAME' : "\\\"" + os.path.basename(f) + "\\\""})
O_FILES = [os.path.splitext(f)[0] + '.o' for f in CPP_FILES]
env.Program('myprogram', O_FILES)
This lets me define things on a per-file basis without listing the files out individually.
Perhaps the following? (Haven't tried it, but something along those lines should work)
env.Program('filename.c',CPPDEFINES='-DBASE_FILE_NAME=\"$SOURCE\"')
Ok so I kinda dropped the ball. I was trying to understand how things work. I had a few html files on my computer that I was trying to rename as txt files. This was strictly a learning exercise. Following the instructions I found here using this code:
for file in *.html
do
mv "$file" "${file%.html}.txt"
done
produced this error:
mv: rename *.html to *.txt: No such file or directory
Long story short I ended up going rogue and renaming the html files, as well as a lot of other non html files as txt files. So now I have files labeled like
my_movie.mp4.txt
my_song.mp3.txt
my_file.txt.txt
This may be a really dumb question but.. Is there a way to check if a file has two extensions and if yes remove the last one? Or any other way to undo this mess?
EDIT
Doing this find . -name "*.*.txt" -exec echo {} \; | cat -b seems to tell me what was changed and where it is located. The cat -b part is not necessary but I like it. This still doesn't fix what I broke though.
I'm not sure if terminal can check for extensions "twice", but you can check for . in every name an if there's more than one occurence of ., then your file has more extensions. Then you can cut the extension off with finding first occurence of . in a string when going backwards... or last one if checking characters in string in a normal way.
I have a faster option for you if you can use python. You can strip the extension with:
for file in list_of_files:
os.rename(file,os.path.splitext(file)[0])
which can give you from your file.txt.txt your file.txt
Example:
You wrote that your command tells you what has changed, so just take those changed files and dump them into a file(path to file per line). Then you can easily run this:
with open('<path to list>') as f:
list_of_files = f.readlines()
for file in list_of_files:
os.rename(file.strip('\n'), os.path.splitext(file.strip('\n'))[0])
If not, then you'd need to get the list from python:
import os
results = []
for root, folder, filenames in os.walk(<your path to folder>):
for filename in filenames:
if filename.endswith('.txt.txt'):
results.append(os.path.join(root, filename))
With this you got a list of files ending with .txt.txt like this <your folder>\\<path_to_file>.
Get a path to your directory used in os.walk() without folder's name(it's already in list) so it'll be like this:
e.g. os.walk('/home/me/directory') -> path='/home/me/' and res is item already in a list, which looks like directory/...
for res in results:
path = '' # set the path here
file = os.path.join(path,r)
os.rename(file, os.path.splitext(file)[0])
Depending on what files you want to find change .txt.txt in if filename.endswith('...') to whatever you like and os.rename() will take file's name without extension which in your case means it strips the additional extension you don't want to have.
I'm writing a script that needs to find a file in a directory based on the user input. That file contains a filepath, and I need to use that filepath as a variable so I can use it later in a mv command. So far :-
read x
path = `cat ~/filepaths/$x`
Later it needs to move a file from trash using the filepath read from this file
mv ~/trash/$x $path
Currently, it doesn't appear to work, and hangs when it runs. Is there something stupid I've missed here?
EDIT: Solved, was a stupid syntax mistake. Thanks for your help!
Remove the spaces around the assignment:
path=`cat ~/filepaths/$x`
or:
path=$(< ~/filepaths/$x)