Unable to copy files of certain extension in Python using loop - python-2.7

I want to loop through the files present in Audio_files folder and check if it is raw file or wave file and put it in the respective directories.
Here is my code:
import shutil
import os
source = os.listdir("/home/GM/codec_implement/Audio_files/")
destination = "/home/GM/codec_implement/raw_files/"
destination2 = "/home/GM/codec_implement/raw_files/wave_files/"
for files in source:
if files.endswith(".wav"):
shutil.copy(files,destination)
elif files.endswith(".raw"):
shutil.copy(files,destination)
else:
print "Invalid format"
Please let me know where I am making mistake. Error i get is:
Traceback (most recent call last): File "./checkaudiofiles.py", line
12, in shutil.copy(files,destination) File
"/usr/lib/python2.7/shutil.py", line 119, in copy copyfile(src, dst)
File "/usr/lib/python2.7/shutil.py", line 82, in copyfile with
open(src, 'rb') as fsrc: IOError: [Errno 2] No such file or directory:
'test_sound.wav'

The error means that the test_sound.wav file is not on that directory. These file might be removed between the two proces or the os.listdir() and the shutil.copy() don't list the files the same way.

Related

Creating folders on the BeagleBone Black in Python

I have code in Pyhton(2.7) on a beagle bone black to create folders that I copy fills of data to. These folders are mounted to the micro-Sd card(archive) and a thumb drive(live data copy). The file is being made in my working dir.
Code:
#staticmethod # Creates a folder if not present
def create_folder(folder_name):
directory = os.path.dirname(folder_name)
try:
os.path.exists(directory)
print("Folder failed")
except:
os.makedirs(directory, 0o777)
print("Folder created")
Error:
Traceback (most recent call last):
File "/var/lib/cloud9/TEMS_Operations/System_Files.py", line 125, in <module>
temp.create_folder(temp.main_folder)
File "/var/lib/cloud9/TEMS_Operations/System_Files.py", line 41, in create_folder
directory = os.path.dirname(folder_name)
File "/usr/lib/python2.7/posixpath.py", line 122, in dirname
i = p.rfind('/') + 1
AttributeError: 'function' object has no attribute 'rfind'
Any Suggestions?
Test program:
def test(self): # System file test
name1 = self.alarm_file()
print(name1)
name2 = self.data_file()
print(name2)
name3 = self.main_folder()
print(name3)
name4 = self.arch_folder()
print(name4)
self.create_data_file(name2)
self.create_alarm_file(name1)
self.create_folder(name3)
self.create_folder(name4)
file_to = name3 + name1
file_from = mane4 +name1
self.copyfile(file_from, file_to)
temp = SystemFiles("ZapOFS", "ZapLab")
print(os.getcwd())
temp.test()
Errors:
/media/mmc/2019/1
/media/usb/2019/1
File created
File created
<type 'str'>
Folder failed
<type 'str'>
Folder failed
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/ikpdb.py", line 1866, in main
ikpdb._runscript(mainpyfile)
File "/usr/local/lib/python2.7/dist-packages/ikpdb.py", line 1415, in _runscript
exec(statement, globals, locals)
File "<string>", line 1, in <module>
File "/var/lib/cloud9/TEMS_Operations/System_Files.py", line 132, in <module>
temp.test()
File "/var/lib/cloud9/TEMS_Operations/System_Files.py", line 127, in test
copyfile(file_from, file_to)
File "/usr/lib/python2.7/shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: '/media/usb/2019/1ZapOFS_ZapLab_Alarm_File_2019_1.csv'
[IKPdb-g] 16:34:52,604104 - INFO - Uncaught exception. Entering post mortem debugging
The only way to allow the creation of folders in python on the mounted MMC and/or USB drives on the BeagleBone black is to remove the sudo password for the current users and add -rw permissions for the program.
# sudo echo "debian ALL=NOPASSWD: ALL" >>/etc/sudoers
Not what I was hoping for, but the only way i can find.
https://elinux.org/Beagleboard:BeagleBoneBlack_Debian

OSError: libmediainfo.so.0: cannot open shared object file: No such file or directory from aws lambda

I am using pymediainfo in lambda function , and I have followed the answer from this so question .
The function has the below code
from pymediainfo import MediaInfo
s3_bucket_file_key = 'https://s3-region.amazonaws.com/sample-bucket/sample_video.mov'
media_info = MediaInfo.parse(s3_bucket_file_key)
media_info_json = media_info.to_json()
Can someone please help me , the sample bucket is public , and I can run this code on my system . but getting the below error from Cloudwatch in aws-lambda.
It seems like libmediainfo is a os related package, I am not sure how to export it to the python deployment package.
anupam:Videos$ apt-cache search libmediainfo
libmediainfo-dev - library reading metadata from media files -- headers
libmediainfo-doc - library for reading metadata from media files -- documentation
libmediainfo0v5 - library for reading metadata from media files -- shared library
error
libmediainfo.so.0: cannot open shared object file: No such file or directory: OSError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 166, in lambda_handler
media_info = MediaInfo.parse(key)
File "/var/task/pymediainfo/__init__.py", line 183, in parse
lib = cls._get_library(library_file)
File "/var/task/pymediainfo/__init__.py", line 155, in _get_library
return CDLL("libmediainfo.so.0")
File "/usr/lib64/python2.7/ctypes/__init__.py", line 357, in __init__
self._handle = _dlopen(self._name, mode)
OSError: libmediainfo.so.0: cannot open shared object file: No such file or directory
When I added libmediainfo.so.0 manually to the command
media_info = MediaInfo(video_file, library_file='path/to/libmediainfo')
I am getting the below error now for libzen.so.0
libzen.so.0: cannot open shared object file: No such file or directory: OSError
Traceback (most recent call last):
File "/var/task/erlabs.py", line 166, in lambda_handler
media_info = MediaInfo.parse(key,library_file='libmediainfo.so.0')
File "/var/task/pymediainfo/__init__.py", line 183, in parse
lib = cls._get_library(library_file)
File "/var/task/pymediainfo/__init__.py", line 146, in _get_library
return CDLL(library_file)
File "/usr/lib64/python2.7/ctypes/__init__.py", line 357, in __init__
self._handle = _dlopen(self._name, mode)
OSError: libzen.so.0: cannot open shared object file: No such file or directory

create file containing '/' in file name in python

how can I create a file in python if the filename contains '/'
url='https://www.udacity.com/cs101x/index.html'
f=open(url,'w')
f.write('123')
f.close()
above code produces an error as
Traceback (most recent call last):
File "9.py", line 2, in <module>
f=open(url,'w')
IOError: [Errno 22] invalid mode ('w') or filename:https://www.udacity.com/cs101x/index.html'
Use os.path.basename() to isolate the filename.
import os
url='https://www.udacity.com/cs101x/index.html'
filename = os.path.basename(url)
f=open(filename,'w')
f.write('123')
f.close()
This will create a file called index.html

When i tried to rename a txt file in pythonwin

I wrote a script to rename a txt file in pythonwin as below.
import os
os.rename("northrdge.txt","northrdgechg.txt")
the above text file is in the path:C:\Users\gmayil\Desktop\northrdge.txt.
after this when i run the script i met below error:
Can anyone please help me on this ?
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 433, in ImportFile
exec codeObj in __main__.__dict__
File "<auto import>", line 1, in <module>
File "C:\Python27\Tools\gopi\renamefile.py", line 2, in <module>
os.rename("northrdge.txt","northrdgechg.txt")
WindowsError: [Error 2] The system cannot find the file specified
Your python-file lies in "C:\Python27\Tools\gopi\renamefile.py", but you say your txt-file is in "C:\Users\gmayil\Desktop\". If you pass a relative path, python searches in its own directory, which is "C:\Python27\Tools\gopi\".
So all you have to do is giving the complete path:
os.rename("C:\Users\gmayil\Desktop\northrdge.txt", "C:\Users\gmayil\Desktop\northrdgechg.txt")

Python Transfering files to and from the remote machine

i want to transfer a file local to server machine.
import os
import paramiko
local_path = "/home/e100075/python/ss.txt"
remote_path = "/home/developers/screenshots/"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls /tmp')
print "output", ssh_stdout.read()
#Reading output of the executed command
error = ssh_stderr.read()
#Reading the error stream of the executed command
print "err", error, len(error)
#Transfering files to and from the remote machine
sftp = ssh.open_sftp()
sftp.get(remote_path, local_path)
sftp.put(local_path, remote_path)
sftp.close()
ssh.close()
After run the program. I got the errors below
Traceback (most recent call last):
File "file_copy.py", line 21, in <module>
sftp.get(remote_path, local_path)
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 606, in get
fr = self.file(remotepath, 'rb')
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 245, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 635, in _request
return self._read_response(num)
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 682, in
_read_response
self._convert_status(msg)
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 708, in
_convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
If you know the answer. please let me know.
Thanks for reading.
If you want to put a file to the server you probably will need
sftp.put(local_path, remote_path)
not
sftp.get(remote_path, local_path)
You need to give file name also, otherwise it will throw errors
sftp.put('filename.txt','/home/user/performance/destination.txt')
where 'filename.txt' must be in current directory or else give full path