Python starter program : Moving files - python

Looking to make some use out of Python! I wanted to write a script to move all those carelessly placed .jpg files from my desktop.
Thing, is the script I'm using doesn't seem to be finding anything.
thoughts?
import os, shutil, glob
dst_fldr = "~/path/Desktop/newfolder";
for jpg_file in glob.glob("~/path/Desktop"+"\\*.jpg"):
print jpg_file + "will be moved to " + dst_fldr
shutil.move(jpg_file, dst_fldr);

~ is not a character that glob understands (it's a character that bash understands and expands). You'll have to provide a full path.
dst_fldr = "/path/to/Desktop/newfolder";
In addition, you'd want to modify the wildcard search, to something like this:
glob.glob("/path/to/Desktop/*.jpg"):
If your python script resides in Desktop, you can drop the /path/to/Desktop part of the path in both cases.
With these changes in place, I believe you're good to go.

Related

Opening apps without the directory (or with replacement of users folder) in Python

So, I want to make a python program which can locate and open Discord & Minecraft and open it on other computers.
And itself it's pretty easy to do if you have a directory in which the files are located, but my problem is I want to share this file with other people, and I want it to work on their PC too. This is my code:
import subprocess
subprocess.run("C:\\Users\\1\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe")
subprocess.run("E:\Geim\Minecraft Launcher\MinecraftLauncher.exe")
My Minecraft location is sligtly weird cause I need more memory so look only only on the discord example, if the solution would be replacing the users folder I'll deal with that
So the problem with this code again is that it works only on my computer since my users directory is named "1"
I also tried using os and retrieving the name which windows identifies Minecraft using Winapps module ("Minecraft Launcher") and while it works for chrome os can't read spaces and replacing it with "-" or "_", or simply lowercasing the letters didn't work
import os
os.system("minecraft launcher") # doesn't work
I also found this intersting chunk of code but I couldn't implement it in directory in the subprocess
from pathlib import Path
home = str(Path.home())
subprocess.run("C:\\Users\\" + home + "\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe") # doesn't work
It seems to be an easy problem for more skilled programmers so I hope to see help soon, thank you.
Edit: I was able to solve the problem by using pathlib and replacing "/" with "\", however I'd still like to receive an answer where it can be found in any not set directory (like mine "E\Geim...)
Here's my working code:
import subprocess
from pathlib import Path
home = str(Path.home())
home = home.replace("\\", "/")
subprocess.run(home + "\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe")
subprocess.run(home + "\\AppData\\Roaming\\.minecraft\\TLauncher.exe")

Can i shorten a file location to the .py files location

first post here so sorry if it's hard to understand. Is it possible to shorten the directory in python to the location of the .py file?. For example, if I wanted to grab something from the directory "C:\Users\Person\Desktop\Code\Data\test.txt", and if the .py was located in the Code folder, could I shorten it to "\data\test.txt". I'm new to python so sorry if this is something really basic and I just didn't understand it correctly.
I forgot to add i plan to use this with multiple files, for example: "\data\test.txt" and \data\test2.txt
import os
CUR_FILE = os.path.abspath(__file__)
TARGET_FILE = "./data/test.txt"
print(os.path.join(CUR_FILE, TARGET_FILE))
With this, you can move around your Code directory anywhere and not have to worry about getting the full path to the file.
Also, you can run the script from anywhere and it will work (you don't have to move to Code's location to run the script.
You can import os and get current working directory ,this will give you the location of python file and then you can add the location of folder data and the file stored in that ,code is given below
import os
path=os.getcwd()
full_path1=path+"\data\test.txt"
full_path2=path+"\data\test2.txt"
print(full_path1)
print(full_path2)
I think this will work for your case and if it doesn't work then add a comment

How to access file in parent directory using python?

I am trying to access a text file in the parent directory,
Eg : python script is in codeSrc & the text file is in mainFolder.
script path:
G:\mainFolder\codeSrc\fun.py
desired file path:
G:\mainFolder\foo.txt
I am currently using this syntax with python 2.7x,
import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
Although this works fine, is there a better (prettier :P) way to do this?
While your example works, it is maybe not the nicest, neither is mine, probably. Anyhow, os.path.dirname() is probably meant for strings where the final part is already a filename. It uses os.path.split(), which provides an empty string if the path end with a slash. So this potentially can go wrong. Moreover, as you are already using os.path, I'd also use it to join paths, which then becomes even platform independent. I'd write
os.path.join( os.getcwd(), '..', 'foo.txt' )
...and concerning the readability of the code, here (as in the post using the environ module) it becomes evident immediately that you go one level up.
To get a path to a file in the parent directory of the current script you can do:
import os
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'foo.txt')
You can try this
import environ
environ.Path() - 1 + 'foo.txt'
to get the parent dir the below code will help you:
import os
os.path.abspath(os.path.join('..', os.getcwd()))

How to format the beginning a loop correctly?

I have a program which I designed both for myself and my colleague to use, with all the data being stored in a directories. However, I want to set up the loop so that it work both for me and him. I tried all of these:
file_location = glob.glob('/../*.nc')
file_location = glob('/../*.nc')
But none of them are picking up any files. How can I fix this?
You can get a directory relative to a user's home (called ~ in the function call) using os.path.expanduser(). In your case, the line would be
file_location = glob.glob(os.path.expanduser('~/Dropbox/Argo/Data/*.nc'))
Usually is a good practice not hardcoding paths if you're going to use your paths for other tasks which need well-formed paths (ie: subprocess, writing paths to shell scripts), I'd recommend to manage paths using the os.path module instead, for example:
import os, glob
home_path = os.path.expanduser("~")
dropbox_path = os.path.join(home_path, "Dropbox")
good_paths = glob.glob(os.path.join(dropbox_path,"Argo","Data","*.nc"))
bad_paths = glob.glob(dropbox_path+"/Argo\\Data/*.nc")
print len(good_paths)==len(bad_paths)
print all([os.path.exists(p) for p in good_paths])
print all([os.path.exists(p) for p in bad_paths])
The example shows a comparison between bad and well formed paths. Both of them will work, but good_paths will be more flexible and portable in the long term.

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.

Categories

Resources