Generating directories/sub-directories and files - python

Hi I am currently a beginner to the python language, it is also my first language too. I need some help I am finding it difficult to know what to use to generate permanent directories sub directories and files, for eg; I want the path to generate whatever path i enter if the directories etc. don't exist, i want them created, so I enter C:\user\python\directory\sub-directory\file, then i cant workout what i should import to do the following job.
I am using Python 3.2, any advice?

You can do:
import os
os.makedirs('a/b/c', exist_ok=True)
http://docs.python.org/py3k/library/os.html

f = open("c:\file\path","w")
f.write("content of file")
First, you open the file, storing it in variable f.
You then write to it, using f.write()
Python will create the file and path if it does not exist, I think. (I am sure I've done this before, but I can't remember)
When you have finished using the file, you should use
f.close()
to close the file safely.

Related

How to write a program that references to file, where the directory changes

I'm currently working on a program that uses databases and all that kind of stuff for a friend of mine. Now while doing my basic planning of what I will need to do, I thought to myself how will I get the program to connect to the right MS Access database if I hard code the path to my own personal computer? Because ill be using pyinstaller to package the program for him.
Do I need to build the directory in a dynamic way that uses the path of the current script, and then some string manipulation of that path to get the right file?
i.e.
import os
file_path = os.path.realpath(__file__)
# Using prior knowledge knowing the file name length is 7
file_path = file_path[:-7]
#appending the path string to point to the database
file_path = file_path + "/databases/test.accdb"
Or will the program still someway find its way to that database?
You can use a: os.walk(...) function to locate specified name file or every database file in specified directories. Next user can choose which file is correct

Call all files from a menu

I've got a task to do that is crushing my head. I have five .py documents and I want to make a menu in another .py so I can run any of them by introducing a string inside an input() but don't really see the way to do that and I don't know if there is somehow I can.
I have tried import every file to the 6th file but I don't even know how to start.
I would like it just to be seen as simple as it can sound, but yet I find it really hard.
If you just want to run them, then try this:-
import os
file_path = input("Enter the path of your file = ")
os.system(file_path)
If the file that you are trying to execute is not in the current
directory, i.e. doesn't exist in the same folder as the currently
executing python file, then you have to provide it's full path.
Path Format:-. C:\Users\lmYoona\OneDrive\Desktop\example.py
If the python file you are trying to execute is in the same directory as
the currently executing python file, then abstract name will also
work
Path Format:- example.py
P.S.:- I would only recommend this method if all you want is just to execute the other python file, rather then importing stuff from it.

How to open any program in Python?

Well I searched a lot and found different ways to open program in python,
For example:-
import os
os.startfile(path) # I have to give a whole path that is not possible to give a full path for every program/software in my case.
The second one that I'm currently using
import os
os.system(fileName+'.exe')
In second example problem is:-
If I want to open calculator so its .exe file name is calc.exe and this happen for any other programs too (And i dont know about all the .exe file names of every program).
And assume If I wrote every program name hard coded so, what if user installed any new program. (my program wont able to open that program?)
If there is no other way to open programs in python so Is that possible to get the list of all install program in user's computer.
and there .exe file names (like:- calculator is calc.exe you got the point).
If you want to take a look at code
Note: I want generic solution.
There's always:
from subprocess import call
call(["calc.exe"])
This should allow you to use a dict or list or set to hold your program names and call them at will. This is covered also in this answer by David Cournapeau and chobok.
You can try with os.walk :
import os
exe_list=[]
for root, dirs, files in os.walk("."):
#print (dirs)
for j in dirs:
for i in files:
if i.endswith('.exe'):
#p=os.getcwd()+'/'+j+'/'+i
p=root+'/'+j+'/'+i
#print(p)
exe_list.append(p)
for i in exe_list :
print('index : {} file :{}'.format(exe_list.index(i),i.split('/')[-1]))
ip=int(input('Enter index of file :'))
print('executing {}...'.format(exe_list[ip]))
os.system(exe_list[ip])
os.getcwd()+'/'+i prepends the path of file to the exe file starting from root.
exe_list.index(i),i.split('/')[-1] fetches just the filename.exe
exe_list stores the whole path of an exe file at each index
Can be done with winapps
First install winapps by typing:
pip install winapps
After that use the library:
# This will give you list of installed applications along with some information
import winapps
for app in winapps.list_installed():
print(app)
If you want to search for an app you can simple do:
application = 'chrome'
for app in winapps.search_installed(application):
print(app)

FileNotFoundError WinError 3

I'm trying to learn how to edit files, but I'm a bit of a python novice, and not all that bright, so when I get a FileNotFoundError I can't figure out how to fix it despite several searches on the interwebz.
import os
old = 'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n'
new = 'Users\My Name\Pictures\2013\Death_Valley_1'
os.rename(old, new)
'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n' is a relative path.
Unless you are running your code from the directory that contains the Users dir (which if you are using Windows would most probably be the root C: dir), Python isn't going to find that file.
You also have to make sure to include the file extension if it has any.
There are few ways to solve this, the easiest one will be to use the absolute paths in your code, ie 'C:\Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n.jpg'.
You will also want to use r before the paths, so you want need to escape every \ character.
import os
old = r'C:\Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n.jpg'
new = r'C:\Users\My Name\Pictures\2013\Death_Valley_1.jpg'
os.rename(old, new)
This of course assumes your drive letter is C.

How to create files to and open files from a sub directory in Python?

I am a beginner at Python programming (2.7; and Pygame) and I was wondering; how do you create and read files from a sub directory? In other words, I want to take sprite images, data, BGM, etc. from a sub directory named 'Data'. So, for example, if I wanted to use Pygame to open a sprite file in the sub directory 'Data', how would I do that?
What I have so far for the sprite-loading is:
char_idle = pygame.image.load("char_idle.png")
Use the os.path.join function to get the path of the file.
Add
import os
at the beginning of your code. Use it like this:
char_idle = pygame.image.load(os.path.join("Data", "char_idle.png"))
You could also provide the path as "Data/char_idle.png" (on Linux) or "Data\char_idle.png" (Windows), but it makes yout code less portable, so better use os.path.join.

Categories

Resources