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")
Related
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.
I'm trying to create a python script called script.py with new_directory function that creates a new directory inside the current working directory, then creates a new empty file inside the new directory, and returns the list of files in that directory.
The output I get is ["script.py"] which looks correct but gives me this error:
RuntimeErrorElement(RuntimeError,Error on line 5:
directory = os.mkdir("/home/PythonPrograms")
FileExistsError: [Errno 17] File exists: '/home/PythonPrograms'
)
import os
def new_directory(directory, filename):
if os.path.isdir(directory) == False:
directory = os.mkdir("/home/PythonPrograms")
os.chdir("PythonPrograms")
with open("script.py", "w") as file:
pass
# Return the list of files in the new directory
return os.listdir("/home/PythonPrograms")
print(new_directory("PythonPrograms", "script.py"))
How do I correct and why is this wrong?
As others have said, it is hard to debug without the error. In the right cercumstances, your code will work without errors. As #Jack suggested, I suspect you're current directory is not /home. This means you've created a directory called PythonPrograms in /home directory. os.chdir("PythonPrograms") is trying to change the directory to <currentDirectory>/PythonPrograms, which doesn't exist.
I have tried to rework your code (without completely changing it), into something that should work in all cases. I think the lesson here is, work with the variables you already have (i.e. directory), rather than hardcoding it into the function.
import os
def new_directory(directory, filename):
if not os.path.isdir(directory):
# Create directory within current directory
# This is working off the relative path (from your current directory)
directory = os.mkdir(directory)
# Create file if does not exist
# this is a one-liner version of you with...pass statement
open(os.path.join(directory, filename), 'a').close()
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
I hope that helps.
I'm guessing the error you're getting is because you're not able to switch directories to PythonPrograms? This would be because your python current working directory does not contain it. If you more explicitly write out the directory you want to switch to, for example putting os.chdir("/home/PythonPrograms"), then it may work for you.
Ideally you should give us any stack traces or more info on the errors, though
I'm not sure why in your code you have with open("script.py", "w") as file: pass,
but here is mt way:
import os
os.mkdir('.\\Newfolder') # Create a new folder called Newfolder in the current directory
open('.\\Newfolder\\file.txt','w').close() # Create a new file called file.txt into Newfolder
print(os.listdir('.')) # Print out all the files in the current directory
I have a program that relies on user input to enter files for the program to open in Python 2.7.11. I have all of those files in a sub-directory called TestCases within the original directory Detector, but I can't seem to access the files in TestCases when running the program from the super-directory. I tried to use os.path.join but to of no avail. Here is my code:
import os.path
def __init__(self):
self.file = None
os.path.join('Detector', 'TestCases')
while self.file == None:
self.input = raw_input('What file to open? ')
try:
self.file = open(self.input, 'r')
except:
print "Can't find file."
My terminal when I run the program goes as follows:
>>> What file to open? test.txt # From the TestCases directory
>>> Can't find file.
>>> What file to open? ...
Am I using os.path.join incorrectly? I thought it was supposed to link the two directories so that files could be accessed from the sub-directory while running the program from the super-directory.
You are using os.path.join('Detector', 'TestCases'), that should return 'Detector/TestCases', but you aren't storing that variable anywhere.
I suppose that you are in Detector directory and you want to open files in TestCases. I that case you can use path join (It concatenates its arguments and RETURNS the result):
import os.path
file = None
while not file:
input = raw_input('What file to open? ')
try:
filepath = os.path.join('TestCases', input)
file = open(filepath, 'r')
except IOError:
print "Can't find " + input
I have stored the result of os.path.join so you could see that it doesn't change the directory, it just concatenates its arguments, maybe you was thinking that function will change the directory, you can do it with os.chdir.
Try it first in a simple script or in the terminal, it will save many headaches.
The documentation about os.path.join
Join one or more path components intelligently. The return value is the concatenation of path...
It seems like you expect it to set some kind of PATH variable or affect the current working directory. For a first start it should be sufficient to add something like this to your code:
open(os.path.join("TestCases",self.input), 'r')
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.
I am trying to write a detector that checks if a certain directory can be deleted using shutil.rmtree. I have a partial code finished as below that now works partial.
This code is now able to gives warning when any .exe files under the target folder is still running. But, this code is not yet able to flag warnings if any particular file under a folder is opened by an editor (which is another cause that makes a directory not deletable). Any guidance will be appreciated. Thanks in advance
Note: I've used open method to check for any locked file.
def list_locked_files(dir):
isLocked = False
for name in os.listdir(dir):
uni_name = unicode(name)
fullname = dir + u'/' + uni_name
if os.path.isdir(fullname):
list_locked_files(fullname)
else:
try:
f = open(fullname, 'r+')
f.close()
except IOError:
print fullname + u' is locked!'
isLocked = True
if isLocked is True:
print u'Please close the files/dir above !'
sys.exit(0)
It is not necessarily possible to determine whether a file deletion will succeed or fail on Windows. The file could be opened in a fully permissive share mode which means another attempt to open the file will succeed (no matter what kind of access you request).
The only way to tell whether a file can be deleted is to actually try it.
Even if there were an accurate way to tell beforehand, once you get the information it is instantly out of date. For example, after you call list_locked_files, a program could open another file in that directory which would cause rmtree() to fail.