dealing with spaces in file names - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: dealing with spaces in file names (/thread-10689.html) |
dealing with spaces in file names - AceScottie - May-31-2018 example import os file = "C:\\test file.txt" os.system("start '" +file +"'") im just looking to open any file with windows default applications
RE: dealing with spaces in file names - snippsat - Jun-01-2018 Should not use os.system() anymore. Quote:os.system() and os.popen*() have been deprecated since Python 2.6 in favor of the subprocess moduleThere can be some problem with space in filename when using subprocess module. So this open in default applications and can handle space in file name. import subprocess subprocess.run(('cmd', '/C', 'start', '', r'E:\env\test file.txt'))A trick that also can work cross platform. import webbrowser webbrowser.open(r'E:\env\test file.txt')Linux Mint test ok. import webbrowser webbrowser.open(r'/home/mint/test file.txt')Windows only. import os os.startfile(r'E:\env\test file.txt', 'open') RE: dealing with spaces in file names - AceScottie - Jun-01-2018 I have tried the subprocess module as well with the same result. The issue is the r"string space". I never actually define the string manually it's just pulled from os.listdir() so I can't add the r to the start of the string RE: dealing with spaces in file names - wavic - Jun-01-2018 As I know Windows paths are binary. So instead of r'' prefix, try b''. I do not know if that is changed. I didn't use Windows for years. RE: dealing with spaces in file names - snippsat - Jun-01-2018 (Jun-01-2018, 12:57 PM)AceScottie Wrote: I never actually define the string manually it's just pulled from os.listdir() so I can't add the r to the start of the string os.listdir() just return filename,so why should you add r (raw string)?If you build path yourself then can r or \\ or / just not singel \ because of escape charterer.Maybe i misunderstand you,so it's better that you post code and explain what's not working. Here using listdir and open in Notepad default Windows application. Now i just working from current folder so no path is needed. >>> import webbrowser >>> import os >>> >>> lst = os.listdir('.') >>> lst ['c.py', 'cpt.py', 'f.py', 'html_env', 'path.py', 'test file.txt'] >>> webbrowser.open(lst[-1]) True RE: dealing with spaces in file names - AceScottie - Jun-02-2018 (Jun-01-2018, 01:49 PM)snippsat Wrote:(Jun-01-2018, 12:57 PM)AceScottie Wrote: I never actually define the string manually it's just pulled from os.listdir() so I can't add the r to the start of the string Webbroweser is the best module i was looking for. it fixes the file name issue and also opens the "open with" window for non associated files Thansk |