I have a small Python program. I use the the Windows registry to enable the opening of files using the right-click context menu. My registry entry:
C:\Users\me\projects\mynotepad\notepad.exe "%1"
When I try and open a file with a Hebrew name using my right-click context menu, I get the file name as question marks, and I get an exception while trying to get the file size.
Here is my code:
file_name = sys.argv[1]
file_size = os.path.getsize(unicode(file_name))
I have tried this:
file_name = sys.argv[1].decode("cp1255").encode('utf-8')
file_size = os.path.getsize(unicode(file_name))
But it didn't work.
Any advice?
Turns out it's a problem. See here for the solution. You need to resort to Windows API to get the arguments.
Related
I have no issue with this on Mac. Windows seems to have trouble opening it.
I have a file name eg : stdout_blahblah_2020-08-25T00:00:00.000Z_2020-08-26T00:00:00.000Z.txt
I cant change the file name unfortunately and I have tons of them to open. This is a simple code I wrote:
sysout_filename = "stdout_blahblah_2020-08-25T00:00:00.000Z_2020-08-26T00:00:00.000Z.txt"
sys.stdout = open(sysout_filename, "w")
So how can I open this file without getting OSError.
How can I run a command that requires a filepath that contains spaces when using the start command with os.system
For Example:
# path_d[key] = C:\Users\John\Documents\Some File With Space.exe
path = path_d[key]
os.system("start {0}".format(path))
When I try running it I end up getting an error saying:
Windows cannot find 'C:\Users\John\Documents\Some.'. Make sure you typed the name correctly, and then try again.
i do the following
path = path_d[key]
os.system(r'start "{0}"'.format(path))
so, surround the path with double quotes. that way it will take care of spaces in path.
if there is no default application to open, it might open command prompt. So, if its a text file do the following
os.system(r'notepad "{0}"'.format(path))
You need to properly escape your special characters in path, which might be easily done as such:
path = r"C:\Users\John\Documents\Some File With Space.exe"
To execute it under Windows:
import os
os.system(r"C:\Users\John\Documents\Some File With Space.exe")
EDIT
per request of OP:
path_dict = {"path1": r"C:\Users\John\Documents\Some File With Space.exe"}
os.system('{}'.format(path_dict["path1"]))
I am trying to use Python to open a file for visual browsing, i.e. as if one double clicked a file to view it. I have tried numerous searches but because the words are very similar with doing file I/O I could not come across the appropriate information.
I think this is a very simple question / answer and I apologize if the answer was right in front of my nose.
Ideally it would just be a call on a given file path and Python would know the appropriate application to pair in case it was an extension like .pdf.
os.startfile()
os.system() but the parameters passed varies according to the OS
Windows: Start fileName
Mac: open fileName
Linux: oowriter fileName
: gnome-open fileName
: kde-open fileName etc...
Example:
fileName="file.pdf" //Path to the file
1. os.startfile(fileName)
2. os.system("start %s")%fileName
On Windows you can use os.startfile().
os.startfile("C:\\Users\\your\\file.pdf")
I have this Python script here that opens a random video file in a directory when run:
import glob,random,os
files = glob.glob("*.mkv")
files.extend(glob.glob("*.mp4"))
files.extend(glob.glob("*.tp"))
files.extend(glob.glob("*.avi"))
files.extend(glob.glob("*.ts"))
files.extend(glob.glob("*.flv"))
files.extend(glob.glob("*.mov"))
file = random.choice(files)
print "Opening file %s..." % file
cmd = "rundll32 url.dll,FileProtocolHandler \"" + file + "\""
os.system(cmd)
Source: An answer in my Super User post, 'How do I open a random file in a folder, and set that only files with the specified filename extension(s) should be opened?'
This is called by a BAT file, with this as its script:
C:\Python27\python.exe "C:\Programs\Scripts\open-random-video.py" cd
I put this BAT file in the directory I want to open random videos of.
In most cases it works fine. However, I can't make it open files with Unicode characters (like Japanese or Korean characters in my case) in their filenames.
This is the error message when the BAT file and Python script is run on a directory and opens a file with Unicode characters in its filename:
C:\TestDir>openrandomvideo.BAT
C:\TestDir>C:\Python27\python.exe "C:\Programs\Scripts\open-random-video.py" cd
The filename, directory name, or volume label syntax is incorrect.
Note that the filename of the .FLV video file in that log is changed from its original filename (소시.flv) to '∩╗┐' in the command line log.
EDIT: I learned that the above command line error message is due to saving the BAT file as 'UTF-8 with BOM'. Saving it as 'ANSI or UTF-16' shows the following message instead, but still does not open the file:
C:\TestDir>openrandomvideo.BAT
C:\TestDir>C:\Python27\python.exe "C:\Programs\Scripts\open-random-video.py" cd
Opening file ??.flv...
Now, the filename of the .FLV video file in that log is changed from its original filename (소시.flv) to '??.flv.' in the command line log.
I'm using Python 2.7 on Windows 7, 64-bit.
How do I allow opening of files that have Unicode characters in their filenames?
Just use Unicode literals e.g., u".mp4" everywhere. IO functions in Python will return Unicode filenames back if you give them Unicode input (internally they might use Unicode-aware Windows API):
import os
import random
videodir = u"." # get videos from current directory
extensions = tuple(u".mkv .mp4 .tp .avi .ts .flv .mov".split())
files = [file for file in os.listdir(videodir) if file.endswith(extensions)]
if files: # at least one video file exists
random_file = random.choice(files)
os.startfile(os.path.join(videodir, random_file)) # start the video
else:
print('No %s files found in "%s"' % ("|".join(extensions), videodir,))
If you want to emulate how your web browser would open video files then you could use webbrowser.open() instead of os.startfile() though the former might use the latter internally on Windows anyway.
The error when running the BAT file is because the BAT file itself is saved as "UTF-8 with BOM". The "" bytes are not a corrupted filename, they are the literal first bytes stored in the BAT file. Re-save the BAT file as ANSI or UTF-16, which are the only encodings supported for BAT files.
Either use Unicode literals as described by J. F. Sebastian, or use Python 3, which always uses Unicode.
(For Python 3, your script will need a minor modification: print is a function now, so you have to put parentheses around the parameter list.)
please familiarize yourself to add # -*- coding: utf-8 -*- in your source code,
so python understanding about your unicode.
I would like to give users of my simple program the opportunity to open a help file to instruct them on how to fully utilize my program. Ideally i would like to have a little blue help link on my GUI that could be clicked at any time resulting in a .txt file being opened in a native text editor, notepad for example.
Is there a simple way of doing this?
import webbrowser
webbrowser.open("file.txt")
Despite it's name it will open in Notepad, gedit and so on. Never tried it but it's said it works.
An alternative is to use
osCommandString = "notepad.exe file.txt"
os.system(osCommandString)
or as subprocess:
import subprocess as sp
programName = "notepad.exe"
fileName = "file.txt"
sp.Popen([programName, fileName])
but both these latter cases you will need to find the native text editor for the given operating system first.
os.startfile('file.txt')
From the python docs:
this acts like double clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.
This way if your user changed their default text editor to, for example, notepad++ it would use their preference instead of notepad.
If you'd like to open the help file with the application currently associated with text files, which might not be notepad.exe, you can do it this way on Windows:
import subprocess
subprocess.call(['cmd.exe', '/c', 'file.txt'])
You can do this in one line:
import subprocess
subprocess.call(['notepad.exe', 'file.txt'])
You can rename notepad.exe to the editor of your choice.
Here's somewhat of a cross-platform one (edit if you have any other methods):
import shutil, subprocess, os
file_name = "whatever.txt"
if hasattr(os, "startfile"):
os.startfile(file_name)
elif shutil.which("xdg-open"):
subprocess.call(["xdg-open", file_name])
elif "EDITOR" in os.environ:
subprocess.call([os.environ["EDITOR"], file_name])
If you have any preferred editor, you can just first try opening in that editor or else open in a default editor.
ret_val = os.system("gedit %s" % file_path)
if ret_val != 0:
webbrowswer.open(file_path)
In the above code, I am first trying to open my file in gedit editor which is my preferred editor, if the system does not have gedit installed, it just opens the file in the system's default editor.
If anyone is getting an instance of internet explorer when they use import webbrowser, try declaring the full path of the specified file.
import webbrowser
import os
webbrowser.open(os.getcwd() + "/path/to/file/in/project")
#Gets the directory of the current file, then appends the path to the file
Example:
import webbrowser
import os
webbrowser.open(os.getcwd() + "/assets/ReadMe.txt")
#Will open something like "C:/Users/user/Documents/project/assets/ReadMe.txt"