Python 3 unable to find file - python-3.x

My code is listed below. I am just trying to follow along with a tutorial. I am working on eventually applying this to a long list in a csv format. However, I cannot seem to get this simple code to run without throwing an error. The error is the dreaded FileNotFoundError: [WinError 2] The system cannot find the file specified. Any help is greatly appreciated.
import simplekml
import subprocess
import pandas as pd
# names in a list
names = ['test_1',
'test_2',
'test_3']
# lat and longs
latitudes = [47.547921, 48.018745, 47.982146]
longitudes = [-105.125498, -105.325687, -105.6547821]
# piecing together the name, long, and lat values into variable called locations
locations = pd.DataFrame({'names': names,
'longitudes': longitudes,
'latitudes': latitudes})
# creating an instance of the simplekml class
points_kml = simplekml.Kml()
# iterating over the locations variable
for i in locations.itertuples():
points_kml.newpoint(name=i.names, coords=[(i.longitudes, i.latitudes)])
# assigning the variable points_kml_path to where we want to save the file we are creating
points_kml_path = 'c:/Users/rexmo/Documents/points_kml.kml'
points_kml.save(points_kml_path)
# open with Google Earth Pro
#subprocess.call(['open', points_kml_path])
subprocess.run(['open', points_kml_path])
My traceback error is as follows:
runfile('C:/Users/rexmo/Documents/Work/spotter_problems/untitled0.py', wdir='C:/Users/rexmo/Documents/Work/spotter_problems')
Traceback (most recent call last):
File "C:\Users\rexmo\Documents\Work\spotter_problems\untitled0.py", line 31, in <module>
subprocess.run(['open', points_kml_path])
File "C:\Users\rexmo\anaconda3\lib\subprocess.py", line 488, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\rexmo\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
super(SubprocessPopen, self).__init__(*args, **kwargs)
File "C:\Users\rexmo\anaconda3\lib\subprocess.py", line 800, in __init__
restore_signals, start_new_session)
File "C:\Users\rexmo\anaconda3\lib\subprocess.py", line 1207, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
The file is being written to the directory listed in the code. I can double click the file in the folder and it is opened in Google Earth as expected. I am at a loss as to what to do.

You could try pathlib?
from pathlib import Path
# Replace this line
points_kml_path = 'c:/Users/rexmo/Documents/points_kml.kml'
# With this
points_kml_path = Path.home() / 'Documents' / 'points_kml.kml'
# Edit, I don't know if you might need it as a string
points_kml_path = Path.home() / 'Documents' / 'points_kml.kml'
points_kml_path = str(points_kml_path)

So I have found 2 different ways to get the result that I wanted, which was simply to fire up Google Earth with the points created in the above script. The first and seemingly less complicated is
import os
os.startfile(points_kml_path)
The other seemingly slightly less complicated way is
# Path to Google Earth exe
earth = 'c:\Program Files\Google\Google Earth Pro\client\googleearth.exe'
subprocess.run([earth, points_kml_path])
It seems weird that I would need to explicitly show the full path to the Google Earth executable. If there is another way I would still be interested in hearing about it.

Related

pathlib.Path.relative_to doesn't resolve path

I'm getting a nonsymetric behavior when using Path.relative_to versus os.path.relpath, see examples below. In Correspondence to tools in the os module, I was guided to believe they behave the same.
I'm working with two paths here
C:\Sync\Rmaster_head_\bin
C:\Sync\installed
I'm using Python 3.9.15.
os.path.relpath
>>> import os.path
>>> import pathlib
>>> start = pathlib.Path(r"../../installed")
>>> rel_path = os.path.relpath(pathlib.Path(r"C:/Sync/Rmaster_head_/bin"), start=start)
>>> rel_path
'..\\..\\..\\..\\Sync\\Rmaster_head_\\bin'
>>> start / pathlib.Path(rel_path)
WindowsPath('../../installed/../../../../Sync/Rmaster_head_/bin')
>>> (start / pathlib.Path(rel_path)).resolve()
WindowsPath('C:/Sync/Rmaster_head_/bin')
pathlib.Path.relative_to in both directions
>>> pathlib.Path(r"C:/Sync/Rmaster_head_/bin").relative_to(pathlib.Path(r"../../installed"))
Traceback (most recent call last):
File "C:\Sync\installed\R2023.1.175_install\sys\python3\x86_64-unknown-winnt_i19v19\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "C:\Sync\installed\R2023.1.175_install\sys\python3\x86_64-unknown-winnt_i19v19\lib\pathlib.py", line 939, in relative_to
raise ValueError("{!r} is not in the subpath of {!r}"
ValueError: 'C:\\Sync\\Rmaster_head_\\bin' is not in the subpath of '..\\..\\installed' OR one path is relative and the other is absolute.
>>> pathlib.Path(r"../../installed").relative_to(pathlib.Path(r"C:/Sync/Rmaster_head_/bin"))
Traceback (most recent call last):
File "C:\Sync\installed\R2023.1.175_install\sys\python3\x86_64-unknown-winnt_i19v19\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "C:\Sync\installed\R2023.1.175_install\sys\python3\x86_64-unknown-winnt_i19v19\lib\pathlib.py", line 939, in relative_to
raise ValueError("{!r} is not in the subpath of {!r}"
ValueError: '..\\..\\installed' is not in the subpath of 'C:\\Sync\\Rmaster_head_\\bin' OR one path is relative and the other is absolute.
I've noticed that the exception says that one of the paths is relative, but it doesn't also work when using full paths.
>>> path1 = pathlib.Path(r"C:\Sync\Rmaster_head_\bin")
>>> path2 = pathlib.Path(r"C:\Sync\installed\R2023.1.175_install\documentation")
>>> os.path.relpath(path1, start=path2)
'..\\..\\..\\Rmaster_head_\\bin'
>>> os.path.relpath(path2, start=path1)
'..\\..\\installed\\R2023.1.175_install\\documentation'
and path1.relative_to(path2) and path2.relative_to(path1) both fail.
What am I missing?
What you're missing is the notes about these methods in the pathlib documentation:
Below the documentation of relative_to():
NOTE: This function is part of PurePath and works with strings. It does not check or access the underlying file structure.
Although it would still be possible to derive the relative path you're looking for based on strings, apparently the method doesn't do that. The example and the error message are clear about this.
That the function is different than os.path.relpath() is also explicitly mentions at the top of the section you mentioned in your question:
Note: Although os.path.relpath() and PurePath.relative_to() have some overlapping use-cases, their semantics differ enough to warrant not considering them equivalent.
Unfortunately, this (along with some other things) means that pathlib cannot be used to fully replace the os functions. In many cases you'll have to use a mix of both :(

How to randomly copy the contents of a text document to my clipboard

This is my original question
The following script copies the text in /home/my_files/document1.txt to my clipboard.
import pyperclip
path = '/home/my_files/document1.txt'
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Let's say /home/my_files/ contains the following five documents:
/home/my_files/document1.txt
/home/my_files/document2.txt
/home/my_files/document3.txt
/home/my_files/image1.jpg
/home/my_files/image2.png
I would like to create a script to randomly copy the contents of one of the three text documents in /home/my_files/ to my clipboard.
Of course the following script does not work but it shows some of the modules I've been experimenting with.
import glob,random,pyperclip
pattern = "*.txt"
path = random.choice((glob.glob(pattern))("/home/my_files/"))
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Do you have any relevant suggestions for me?
I added the subsequent content to my original question above
When I tried the following solution which #Jacob Lee created...
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())
I received the following error message...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
Someone else suggested the following script to me...
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
But that script doesn't work either. I received the following error when I ran that script...
Traceback (most recent call last):
File "abc.py", line 3, in <module>
path = random.choice(glob.glob(pattern))
File "/usr/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
I am confused.
The following successfully copies the entire contents of a random text file in /home/my_files/ to my clipboard
import glob,random,pyperclip
pattern = "/home/my_files/*.txt"
path = random.choice(glob.glob(pattern))
print("copying contents of ", path)
The_text_of_the_file_that_will_be_copied = open(path, 'r').read()
pyperclip.copy(The_text_of_the_file_that_will_be_copied)
Thanks to #Asocia
Thanks to #Asocia for insisting that the script above works correctly. I don't know what I had been doing wrong, but I must have been doing something wrong when I indicated the script above did not work properly.
You're code raises a TypeError: 'list' object is not callable exception when you try to assign path, in this line:
path = random.choice((glob.glob(pattern))("/home/my_files"))
glob.glob() returns a list (possibly empty). (Also, you put the glob.glob() call inside redundant parentheses.) Then, you try to call glob.glob()("/home/my_files/") (in essence, [...](), raising the TypeError exception.
import glob
import random
import pyperclip
files = [os.path.abspath(f) for f in glob.glob("./home/my_files/*.txt")]
path = random.choice(files)
with open(path) as f:
pyperclip.copy(f.read())

Is there a way to specify and then open a file with Python?

I'm attempting to make a program which will allow the user to pick a file from their computer and then open it. I've been trying to do this with Python, and...
filedialog.askopenfilenames()
...with this Tkinter widget.
I can get the filepath from this successfully, but how to I use it to actually open the file? (I'm trying to open it in its default app, not just print it to the Python console.) I've tried using
from subprocess import call
call(['xdg-open','filename'])
with 'files' (the variable that the filename is stored in) replacing 'filename', but I get the following error:
Traceback (most recent call last):
File "/Users/charlierubinstein/Documents/Search Engine.py", line 9, in <module>
call(['xdg-open', files])
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 267, in call
with Popen(*popenargs, **kwargs) as p:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1275, in _execute_child
restore_signals, start_new_session, preexec_fn)
TypeError: expected str, bytes or os.PathLike object, not tuple
my code so far:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from subprocess import call
files = filedialog.askopenfilenames()
call(['xdg-open', files])
window.mainloop()
As stated earlier, ideally this program would let the user pick a file, and then open that file in its default app.
You use askopenfilenames() (with s at the end of name)
It let you select many files so it returns tuple with all selected files - even if you selected only one file
(or empty tuple if you cancel selection)
So you have to get first element from tuple
call(['xdg-open', files[0] ])
Or use askopenfilename() (without s at the end of name) and you will get single string.
filename = filedialog.askopenfilename() # without `s` at the end
call(['xdg-open', filename])

Error when Unzipping with Pyside Qtgui

When I run my program, I get the following error and am not sure on how to correct it. Can someone help with explaining what this error is and how to correct it? Newb here so details are appreciated. Thanks for your time in advance!
Code:
#!/usr/bin/python
import zipfile
from PySide import QtGui
import re
#Select file to extract
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
if (dialog.exec()):
fileName = dialog.selectedFiles()
#Select Directory to extract to
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
if (dialog.exec()):
dirName = dialog.selectedFiles()
print("Extracting.....")
zFile= zipfile.ZipFile(fileName)
zFile.extractall(dirName)
Error output:
Traceback (most recent call last):
File "C:\Users\Jennifer\Documents\BatchScripts\unzip.py", line 22, in <module>
zFile= zipfile.ZipFile(fileName)
File "C:\Python33\lib\zipfile.py", line 933, in __init__
self._RealGetContents()
File "C:\Python33\lib\zipfile.py", line 970, in _RealGetContents
endrec = _EndRecData(fp)
File "C:\Python33\lib\zipfile.py", line 237, in _EndRecData
fpin.seek(0, 2)
AttributeError: 'list' object has no attribute 'seek'
In your file and target directory code blocks, dialog.selectedFiles() returns a list. zipfile.ZipFile can only handle one file at a time, hence your error. To iterate over the list being provided by dialog.selectedFiles(), use the following:
for archive in fileName: # you should probably change it to fileNames to reflect its true nature
zfile = zipfile.ZipFile(archive)
print("Extracting " + str(zfile.filename) + "...")
zfile.extractall(dirName[0]) # also a list, extract to first item and ignore rest
and you should be all set.

python : how to use wave module?

when I try the following program :
import wave
w = wave.open('f.wav', 'r')
for i in range():
frame = w.readframes(i)
the following error comes :
Traceback (most recent call last):
File "F:/Python31/fg.py", line 2, in <module>
w = wave.open('f.wav', 'r')
File "F:\Python31\lib\wave.py", line 498, in open
return Wave_read(f)
File "F:\Python31\lib\wave.py", line 159, in __init__
f = builtins.open(f, 'rb')
IOError: [Errno 2] No such file or directory: 'f.wav'
can u tell me wat could b the reason ???
The file is not in the path you put that Python interpreter can find. Check that f.wav is in the same path of your script (or chance the path in open).
Is not a wave issue at all.
You are running the python script from a directory where no file f.wav exists. It can't find the file to read. Either copy f.wav to that directory or run you script from the directory f.wav is located in.

Resources