The pygame window opens and closes immediately [duplicate] - image

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)

Related

Python on windows removes created file

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.

Moving files with Wildcards in Python

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\\")

How to open a file with a given path?

i'm trying to programm a photo seeker. I have an issue when i wanted to open these photo from a list of path.
I put the list of path in a listBox, so i can click on choosen path and it stocks it in a string variable but i get an issue when i wanted to open the file.
I searched and i found 2 topics on stack overflow :
Python os module open file above current directory with relative path
import os.path
import sys
basepath = os.path.dirname(__file__)
filepath = os.path.abspath(os.path.join(basepath, "HelloWord.txt"))
f = open(filepath, "r")
I get an error :
File "C:/Users/jguillot/Desktop/test002.py", line 6, in <module>
f = open(filepath, "r")
TypeError: an integer is required
I don't understand it.
I also look at this topic :
Open file in a relative location in Python
which have the same solution as the first one.
To understand my error i go on : https://docs.python.org/2/library/os.path.html
I did :
import os
from os import path
os.path.exits('C:\Users\jguillot\Desktop\HelloWord.txt')
It returns me False
But if i try :
os.path.exits('C:\Users\jguillot\Desktop')
It returns me True
os.path.exists(path) :
Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.
(From python manual)
I don't understand this error.
Can you explain to me please?

Accessing files within a parent folder and it's sub-folders using Python

I have a folder which has subfolders containing 1000s of DICOM images which I want to read in from IDLE and analyze.
I have used the following code to find file paths:
import sys
print sys.path
I subsequently tried placing my folder which I want to access in these file paths, however I still can not access the files and I get the following error:
>>> fp = open(fp, 'rb')
IOError: [Errno 2] No such file or directory: 'IM-0268-0001.dcm'
I have also tried:
sys.path.insert(0, 'C:/desktop/James_Phantom_CT_Dec_16th/Images')
But this did not work for me either. Help much appreciated, very frustrated.
(using Python 2.7, 64 bit windows OS).
When opening a file, Python does not search the path. You must specify the full path to open:
d = 'C:/desktop/James_Phantom_CT_Dec_16th/Images'
fp = open(d +'IM-0268-0001.dcm',"rb")
Edit: d is the string that will hold the path so that you don't have to re-type it for each file. fp will hold the file object that you will work with. The "rb" is the way you want to open the file:
r - read
w - write with truncate
a - append
r+ - read and write
Also, if working in windows, add "b" to work with binary files. See here.

Opening Blender (a program) from a specific filepath, relative paths, Unix executable

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:)

Resources