Creating a missing directory / file structure - Python - python

I'm writing a function that does some operations with a .log file: The program checks if /logs/ansible.log exists before proceeding. If /logs/ansible.log doesn't exist, it should go ahead and create the file / directory structure (both don't exist prior).
try:
if not os.path.exists("/logs/ansible.log"):
# create the /logs/ansible.log file
finally:
# do something
I know I can create the ansible.log file with open('ansible.log', 'w') and create the directory with os.makedirs('/logs/'), however how can I simply create '/logs/ansible.log' at once?
*** Assume program is being executed as root

def createAndOpen(filename, mode):
os.makedirs(os.path.dirname(path), exist_ok=True)
return open(filename, mode)
Now, you can open the file and create the folder at once:
with createAndOpen('/logs/ansible.log', 'a') as f:
f.write('Hello world')
Otherwise, this isn’t possible. The operating system does not give you a single function that does this, so whatever else existed that does this would have to have a similar logic as above. Just less visible to you. But since it simply doesn’t exist, you can just create it yourself.

Related

Creating file to specific directory

I'm creating a program to take YouTube videos and convert them into mp3's and store them in a specific folder.
Every time my program is ran, it will make sure the file directory exists as well as the folder and text file inside of it, if not, it will create these. However when running my program, it does in fact create a file in the specified directory, but it will not create the json file (which is where I will store the file path directory so the user doesn't have to input the directory every time).
The program doesn't close, it doesn't throw an error, it just simply does nothing after creating the file. It shows a blinking cursor and just idles. I'm a newbie here so I'm probably missing something very simple but. I can't figure it out, the code I'm supplying below isn't the whole program, just the function that keeps messing up:
def _check_dir_path() -> bool:
if os.path.exists(file_dir):
while True:
song_path = os.path.join(file_dir, "sp_songs")
dir_file = os.path.join(file_dir, "Song File Directory.json")
if os.path.isdir(song_path):
if os.path.isfile(dir_file):
return True
else:
sp_songs = open("sp_songs", "w")
json.dump(path_dir, sp_songs)
sp_songs.close()
continue
else:
os.mkdir(song_path)
continue
I realized I wasn't specifying a directory, I was creating a file in my python project folder but checking for that file in the specified directory which meant it'll never return true:
sp_songs = open("sp_songs", "w")
By replacing 'sp_songs' with 'dir_file' I was specifying the path:
sp_songs = open(dir_file, "w")

Creating files in python in folders that don`t exist [duplicate]

I'm writing a function that does some operations with a .log file: The program checks if /logs/ansible.log exists before proceeding. If /logs/ansible.log doesn't exist, it should go ahead and create the file / directory structure (both don't exist prior).
try:
if not os.path.exists("/logs/ansible.log"):
# create the /logs/ansible.log file
finally:
# do something
I know I can create the ansible.log file with open('ansible.log', 'w') and create the directory with os.makedirs('/logs/'), however how can I simply create '/logs/ansible.log' at once?
*** Assume program is being executed as root
def createAndOpen(filename, mode):
os.makedirs(os.path.dirname(path), exist_ok=True)
return open(filename, mode)
Now, you can open the file and create the folder at once:
with createAndOpen('/logs/ansible.log', 'a') as f:
f.write('Hello world')
Otherwise, this isn’t possible. The operating system does not give you a single function that does this, so whatever else existed that does this would have to have a similar logic as above. Just less visible to you. But since it simply doesn’t exist, you can just create it yourself.

How to create a file in python if it does not exists

I have the following method in Python.
def get_rum_data(file_path, query):
if file_path is not None and query is not None:
command = FETCH_RUM_COMMAND_DATA % (constants.RUM_JAR_PATH,
constants.RUM_SERVER, file_path,
query)
print command
execute_command(command).communicate()
Now inside get_rum_data I need to create the file if it does not exists, if it exists I need to append the data. How to do that in python.
I tried, open(file_path, 'w') , which gave me an exception.
Traceback (most recent call last):
File "utils.py", line 180, in <module>
get_rum_data('/User/rokumar/Desktop/sample.csv', '\'show tables\'')
File "utils.py", line 173, in get_rum_data
open(file_path, 'w')
IOError: [Errno 2] No such file or directory: '/User/rokumar/Desktop/sample.csv'
I though open would create file in write mode.
It shall be as simple as:
fname = "/User/rokumar/Desktop/sample.csv"
with open(fname, "a") as f:
# do here what you want
# it will get closed at this point by context manager
But I would suspect, that you are trying to use not existing directory. Usually, "a" mode creates the file if it can be created.
Make sure, the directory exists.
You can check if all directories in file_path exist prior to trying to write a file.
import os
file_path = '/Users/Foo/Desktop/bar.txt'
print os.path.dirname(file_path)
# /Users/Foo/Desktop
if not os.path.exists(os.path.dirname(file_path)):
os.mkdirs(os.path.dirname(file_path))
# recursively create directories if necessary
with open(file_path, "a") as my_file:
# mode a will either create the file if it does not exist
# or append the content to its end if it exists.
my_file.write(your_text_to_append)
-- Edit: Small and probably unnecessary extension --
expanduser:
In your case, as it turned out that the initial problem was a missing s in the path to the user directory, there is a useful feature for resolving the current users base directory (works for unix, linux and windows): see expanduser from the os.path module. With that you could write your path as path = '~/Desktop/bar.txt' and the tilde (~) will be expanded just like on your shell. (with the additional benefit that if you started your script from another user it would then expand to her home directory.
App config directory:
Since in most cases it is not desirable to write a file to the desktop (*nix systems for instance might not have a desktop installed), there is a great utility function in the click package. If you look at the get_app_dir() function on Github, you can see how they provide expanding to an appropriate app dir and supporting multiple operating systems (the function has no dependencies besides the WIN variable that is defined in the _compat.py module as WIN = sys.platform.startswith('win') and the _posixify() function defined on line 17. Often that's a good starting point for defining an app directory to store certain data in.

How do I decide where to put the file while creating it in python?

With the code open, I can create a new file in the computer. How do i decide which folder it goes? I need to put them in a certain folder when i am creating them. Should I put sth in the brackets?
e.g. open("apple juice. txt", "a")
If you don't specify a path, then the file will be created in the current directory. Where exactly that is depends on how you started the interpreter. For example, when you start Python 3.4 from the Windows Start Menu, then the file will be saved in C:\Python34\.
If you want to specify a certain path, then do so:
f = open(r"C:\Users\David\Python Files\apple juice.txt", "a")
Give the full path:
with open("path_where/to_save/apple_juice.txt", "a") as f:
# do work
with will automatically close your file.
If you are looking for a place for temp files, use the module tempfile.
You can use the function tempfile.gettempdir() to get a path to a folder directory.
You can use tempfile.TemporaryFile() to generate a full path to the place where the temp files are usually stored on your OS.
The method used in either case to generate the temp path is explained here.

Just generate path for a temporary file

As tempfile.mktemp is depreciated in Python 2.7 I generate a unique path to a temporary file as follows:
temp = tempfile.NamedTemporaryFile(suffix=".py")
path_to_generated_py = temp.name
temp.close()
# now I use path_to_gerated_py to create a python file
Is this the recommended way in Python 2.7? As I close the temp file immediately it looks like misusing NamedTemporaryFile....
The direct replacement for tempfile.mktemp() is tempfile.mkstemp(). The latter creates the file, like NamedTemporaryFile, so you must close it (as in your code snippet). The difference with NamedTemporaryFile is that the file is not deleted when closed. This is actually required: your version has a theoretical race condition where two processes might end up with the same temporary file name. If you use mkstemp() instead, the file is never deleted, and will likely be overwritten by the 3rd-party library you use --- but at any point in time, the file exists, and so there is no risk that another process would create a temporary file of the same name.

Categories