So I am trying to move say all files starting with "A" to a certain directory. Now I now Windows command prompt does not support this method:
move A* A_Dir
But could this combined with Python find a way? Or am I gonna have to go through each individual file?
Such as:
contents=os.listdir('.')
for file in content:
if file[0] == 'A':
os.system("move %s A_Dir" % file)
... etc. Is there any other solution that is more simpler and quicker?
-Thanks!
On Windows: This example moves files starting with "A" from "C:\11" to "C:\2"
Option #1: if you are using batch file, create batch file (movefiles.bat) as show below:
movefiles.bat:
move /-y "C:\11\A*.txt" "C:\2\"
Execute this batch file from python script as shown below:
import os
batchfile = "C:\\1\\movefiles.bat"
os.system( "%s" % batchfile)
Option #2: using glob & shutil
import glob
import shutil
for data in glob.glob("C:\\11\\A*.txt"):
shutil.move(data,"C:\\2\\")
If we want to move all files and directory starting with A:
import glob
import shutil
for data in glob.glob("C:\\11\\A*"):
shutil.move(data,"C:\\2\\")
Based on #eryksun comment, I have added if not os.path.isdir(data):, if only files starting with A are required to be moved and in this case, directory will be ignored.
import glob
import shutil
import os
for data in glob.glob("C:\\11\\A*"):
if not os.path.isdir(data):
shutil.move(data,"C:\\2\\")
Related
Import pygame
pygame.init()
BG = pygame.image.load('_pycache_/test_bg.jpg')
def DrawGameWin():
window.blit(BG,(0,0))
pygame.display.update()
DrawGameWin()
The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python file.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. Alternatively, you can create an absolute file path.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path):
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
An alternative solution is to find the absolute path.
If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the relative filepath. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
filePath = os.path.join(sourceFileDir, 'test_bg.jpg')
# filePath = os.path.join(sourceFileDir, '_pycache_/test_bg.jpg')
surface = pygame.image.load(filePath)
The same can be achieved with the pathlib module.
Change the working directory
import os, pathlib
os.chdir(pathlib.Path(__file__).resolve().parent)
or create an absolute filepath:
import pathlib
# [...]
filePath = pathlib.Path(__file__).resolve().parent / 'test_bg.jpg'
surface = pygame.image.load(filePath)
I'm trying to write a file with a python program. When I perform all the actions command line, they all work fine. The file is created.
When I perform the actions in a python script, the file does not exist after the script terminates.
I created a small script that demonstrates the behavior.
import os
import os.path
current_dir = os.getcwd()
output_file = os.path.join(current_dir, "locations.js")
print output_file
f = open(output_file, "w")
f.write("var locations = [")
f.write("{lat: 55.978467, lng: 9.863467}")
f.write("]")
f.close()
if os.path.isfile(output_file):
print output_file + " exists"
exit()
Running the script from the command line, I get these results:
D:\Temp\GeoMap>python test.py
D:\Temp\GeoMap\locations.js
D:\Temp\GeoMap\locations.js exists
D:\Temp\GeoMap>dir locations.js
Volume in drive D is Data
Volume Serial Number is 0EBF-9720
Directory of D:\Temp\GeoMap
File Not Found
D:\Temp\GeoMap>
Hence the file is actually created, but removed when the script terminates.
What do I need to do the keep the file?
Problem was solved by changing firewall settings.
I created this little Python script Essai_Bash.py to make some tests:
#!/usr/bin/python
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('-i', action='store', dest='InputDir', help='Working Directory') # Empty folders for outputs.
parser.add_argument('--version', action='version', version='%(prog)s 0.1')
results = parser.parse_args()
print 'Current input directory =', results.InputDir
dir_path=str(os.path.abspath(results.InputDir)) # Retrieving an output folder name to use as species ID:
path,CodeSp = os.path.split(dir_path)
print "Currently working on species: "+str(CodeSp)
Back to my shell, I type the following command, expecting my script to run on each directory that is present in my "Essai_Bash" folder:
listdir='ls ../Main_folder/' # I first used backtips instead of simple quotes but it did not work.
for dir in $listdir; do ./Essai_Bash.py -i ../Main_folder/$dir; done
I am surely missing something obvious but it does not work. It seems like $listdir is considered as a characters strings and not a list of directories. However, just typing $listdir in my shell actually gives me this list!
Just use glob extension, parsing ls output is not safe.
Also dir variable already contains ../Main_folder/
listdir=( ../Main_folder/*/ )
for dir in "${listdir[#]}"; do ./Essai_Bash.py -i "$dir"; done
I use CMD to run Python scripts, as the following:
C:\Users python babynames.py --summaryfile baby*.html
The outcome is:
OSError: [Errno 22] Invalid argument: 'baby*.html'
What to use to get the list of all matching file names?
there are 2 modules that can help with that:
glob
pathlib
the relevant function in pathlib is also called glob.
here is an example how you could use pathlib:
from pathlib import Path
path = Path('/home/someuser/tmp')
for file in path.glob('*.html'):
print(file)
# -> /home/someuser/tmp/test.html
In my previous question, Open a file from a specific program from python, I found out how to use subprocess in order to open a program (Blender) — well, a specific .blend file — from a specific file path with this code.
import os
import subprocess
path = os.getcwd()
os.system("cd path/")
subprocess.check_call(["open", "-a", os.path.join(path, "blender.app"),"Import_mhx.blend"])
With the help of a guy at a forum, I wanted to use relative paths inside the .blend file, so I changed the code in this way (for Windows)
import os
import subprocess
# This should be the full path to your Blender executable.
blenderPath = "/cygdrive/c/Program Files/Blender Foundation/blender-2.62-release-windows32/blender.exe"
# This is the directory that you want to be your "current" directory when Blender starts
path1 = "/Users/user/Desktop/scenario/Blender"
# This makes makes it so your script is currently based at "path1"
os.chdir(path1)
subprocess.check_call([blenderPath, "Import_mhx.blend"])
and for Mac,
import os
import subprocess
path = os.getcwd()
os.system("cd path/")
print (path)
# This should be the full path to your Blender executable.
blenderPath = path + "/blender.app/Contents/macos/blender"
# This is the directory that you want to be your "current" directory when Blender starts
path1 = "/Users/user/Desktop/scenario/Blender"
# This makes makes it so your script is currently based at "path1"
os.chdir(path1)
subprocess.check_call([blenderPath, "Import_mhx.blend"])
Results:
In Windows, it works fine.
On Macs, the result is that the file is opened, but the program seems not to be opened. It is quite strange, I think.
Questions:
Is there any extension that I should place for the blender (UNIX executable file) in order for it to open?
Is there any other way that I can do it in order to open the program correctly, but also be able to use relative paths inside .blend files?
import os
import subprocess
blenderPath = "./blender.app/Contents/MacOS/blender"
path1 = "./"
os.chdir(path1)
subprocess.check_call([ blenderPath, "Animation.blend"])
Both blender opens perfectly and relative paths inside .blend file work ok:)