IOError: [Errno 22] invalid mode ('rb') or filename - python-2.7

I am a beginner at python and trying to use a very simple shutil module (shutil.copy) to copy databases from multiple folders into a backup folder. I am getting the error below. Any help is appreciated.
# importing os module
import os
#import time module
import time
import datetime
# importing shutil module
import shutil
now = datetime.datetime.now()
timestamp = str(now.strftime("%Y%m%d_%H%M%S"))
source5 = "F:/SHARED/SOP/PRE GO LIVE/TEST CASES & SCENARIOS/MASTER/PRE_GO_LIVE_MASTER.accdb"
dest5 = "F:/SHARED/SOP/SB/Python/Destination/PRE_GO_LIVE_MASTER.accdb_"+timestamp+".accdb"
print("Before copying ")
DB5 = shutil.copy(source5,dest5)
print("After DATABASE has been copied")
Error:
Traceback (most recent call last):
File "C:\Users\sbasava1\Desktop\Python\Final_Attempt.py", line 101, in <module>
DB5 = shutil.copy(source5,dest5)
File "C:\Python27\lib\shutil.py", line 119, in copy
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 22] invalid mode ('rb') or filename:

Check your file path, use double backslashes \\ or a single forward slash / or make your string a raw string r"...".
# Original path - wouldn't work
path = "c:\location\directory"
# Raw string - would work
path = r"c:\location\directory"
# Double slashes - would work
path = "c:\\location\\directory"
# Forward slashes - would work
path = "c:/location/directory"
Consider learning about string literals
If this didn't help leave me a comment, it would also help to see the/part of the code you are working with!
Edit: Running your script didn't give me an issue:
Check if the directory you are trying to create a file in actually exists

Related

ValueError: I/O operation

I see following error when executing this python code. What is issue here?
I have used "sys.stdout.close()" still I see these errors.
#! /usr/bin/python
import sys
a = [ 10, 12, 13, 14]
sys.stdout=open("file.txt","w")
print("++++++++")
print("***xyz***")
print("++++++++")
sys.stdout.close()
for i in a:
print i
Output:
Traceback (most recent call last):
File "./test3.py", line 10, in <module>
print i
ValueError: I/O operation on closed file`
You are trying to write to stdout (your file) after closing it. At line 8 you close the file, and at line 10 you call print.
If you want to write the list a to the file you should close it after the for loop.
Consider using with open because you don't have to worry about closing it. If your list needs to be a list then consider pickling it instead of writing it to a file. Pickling serializes your data.
#!python3
# import module
from os import system
import pickle
# clear the screan
system('cls')
a = [ 10, 12, 13, 14]
# write a list to file, but it has to be written as a string
with open('file.txt', 'w') as wf:
wf.write(str(a))
# when you open your file up, the data is a string
with open('file.txt', 'r') as fp:
for item in fp:
print(item)
print(type(item))
# if you want to retain your data as a list, then pickle it
output = open('file.pkl', 'wb')
pickle.dump(a, output)
output.close()
# open up a pickled file
pkl_file = open('file.pkl', 'rb')
data = pickle.load(pkl_file)
print(data)
print(type(data))
pkl_file.close()

OSError: [Errno 2] No such file or directory on Ubuntu 16.06

Using Ubuntu, am trying to use the scikit-learn examples with this snippet:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Examples of reading texts files and classifying them
"""
from __future__ import division
import datetime
import sklearn.datasets
time1 = datetime.datetime.now()
##from sklearn.datasets import fetch_20newsgroups
######## Reading text files
rootPath = r"/Home/web2py/corpus/20news-18828/"
However, I got this error:
File "/usr/local/lib/python2.7/dist-packages/sklearn/datasets/base.py", line 201, in load_files
folders = [f for f in sorted(listdir(container_path))
OSError: [Errno 2] No such file or directory: '/Home/web2py/corpus/20news-18828/
I am ery new to Ubuntu and scikit-learn stuff. What could be the issue/error and how do I get it solved.?
Thia worked for me:
rootPath =os.getenv('HOME/web2py/corpus/20news-18828')
However, I got this error:
File "/home/mauricewaka/web2py/detscikit.py", line 19, in <module>
twenty_train = sklearn.datasets.load_files(rootPath,categories=categories, shuffle=True, random_state=42)
File "/usr/local/lib/python2.7/dist-packages/sklearn/datasets/base.py", line 201, in load_files
folders = [f for f in sorted(listdir(container_path))
TypeError: coercing to Unicode: need string or buffer, NoneType found
Any Ideas on how to get solve this error?
I tried to use encoding='utf-8', or remove the encoding argument but still got the same error

Error while using device.takeSnapshot() in androidviewclient

I am currently using the following versions
Python - 2.7.10 ( 32 bit , win)
AndroidViewClient - androidviewclient-10.7.1-py2.7.egg
I have a simple program as below
import sys
import os
try:
sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
pass
from com.dtmilano.android.viewclient import ViewClient
device, serialno = ViewClient.connectToDeviceOrExit()
vc = ViewClient(device=device, serialno=serialno)
device.takeSnapshot().save('Menu.png','PNG')
This is giving me the following error
*Traceback (most recent call last):
File "dump.py", line 14, in <module>
device.takeSnapshot().save('Menu.png','PNG')
File "C:\Python27\lib\site-packages\androidviewclient-10.7.1-py2.7.egg\com\dtmilano\android\adb\adbclient.py", line 678, in takeSnapshot
image = Image.open(stream)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 2126, in open
% (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringI object at 0x023462A8>*
The Same snippet code - works for some devices and for some it doesnt
How can i figure out what is wrong with the devices where it doesnt work
Also please help me idetify any configuration issues as i am new to this

IOError: [Errno 22] PyMel/ Python

Good evening SE'ers,
I've got a question that has been bugging me for the last twenty-four hours. I've read up on the issue and my issue seems to be just plain stupid. So, I must be doing something wrong.
FIRST
I'm using xlrd, xlwt and xlutils to create an excel doc and reopen it to check, update and write (save) out over it. Something is causing it to not work correctly and it's apparently only when it saves OVER itself with an updated (copy) workbook.
I got a good piece of information from this "ask", but it doesn't apply to me...
IOError: [Errno 22] invalid mode ('wb') or filename:
SECOND My issue is that I have this as my error:
IOError: [Errno 22] invalid mode ('w+b') or filename: u'D:/LocalData/[username]/Desktop/test1_.xls'
Note, the user name is actually not [username].
The traceback is listed here:
# Error: 22
# Traceback (most recent call last):
# File "<maya console>", line 3, in <module>
# File "D:/LocalData/[username]/Documents/maya/scripts\ExportExcel.py", line 144, in main
# writeExcel()
# File "D:/LocalData/[username]/Documents/maya/scripts\ExportExcel.py", line 107, in writeExcel
# writeInt(wb,wsInt,filePath,detectName,fileName)
# File "D:/LocalData/[username]/Documents/maya/scripts\ExportExcel.py", line 48, in writeInt
# logTheMatList(wb,wsInt,filePath,detectName)
# File "D:/LocalData/[username]/Documents/maya/scripts\ExportExcel.py", line 35, in logTheMatList
# wb.save(filePath+'MaterialList_'+str(detectName)+'.xls')
# File "D:\Program Files\Autodesk\Maya2013\Python\lib\xlwt\Workbook.py", line 696, in save
# doc.save(filename_or_stream, self.get_biff_data())
# File "D:\Program Files\Autodesk\Maya2013\Python\lib\xlwt\CompoundDoc.py", line 262, in save
# f = open(file_name_or_filelike_obj, 'w+b')
EDIT1:
Figured out that I cannot open a file that and overwrite it. I'm not sure why, but if it's the same name and file location, it highly disapproves and provides an error. Does anyone have any suggestions as to how to avoid this obvious issue?
Figured it out on my own.
If you are opening an excel doc to read from and save over while utilizing os, xlrd, xlwt and xlutils... You must follow these instructions (which probably could have been solved by someone who knew less than me ;) ).
import all the important, necessary modules
rb=xlrd.open_workbook([your location here]+[your file name]+'.xls') WARNING do not use on_demand=True, this keeps your file open
os.remove([your location here]+[your file name]+'.xls')
wb=copy(rb)
wb.save([your location here]+[your file name]+'.xls')
This is the most effective way to update a file you created (like a typical save in a program) without "deleting" your file, which, you will be but will be saving a newer copy.

IndexError: too many indices on Python

Using PyDev with an eclipse environment for Python 2.7 on OSX. Trying to count the element in the array and sum up the elements in the array. Getting an error on the index.
import numpy as np
import os
import sys
csv_file_object = fileName = os.path.join('train.csv')
print('Directory separator on your platform ({}): {}'.format(sys.platform, os.sep))
data=[]
for row in csv_file_object:
data.append(row)
data = np.array(data)
number_passengers = np.size(data[0::,0].astype(np.float))
number_survived = np.sum(data[0::,0].astype(np.float))
proportion_survivors = number_survived / number_passengers
Traceback (most recent call last):
File "/Users/scdavis6/Documents/Kaggle/Titanic1.py", line 14, in <module>
number_passengers = np.size(data[0::,0].astype(np.float))
IndexError: too many indices
Let me know if I can provide additional information.
Thank you.
Update:
I made the edits, but got another error about the module not being callable:
Traceback (most recent call last):
File "/Users/scdavis6/Documents/Kaggle/Titanic1.py", line 5, in <module>
csv_file_object = fileName = os.path('train.csv')
TypeError: 'module' object is not callable
Update:
I changed os.path('train.csv') to os.path.join('train.csv'), but got another error about not finding the .csv file.
Traceback (most recent call last):
File "/Users/scdavis6/Documents/Kaggle/Titanic1.py", line 9, in <module>
with open(fileName) as f:
IOError: [Errno 2] No such file or directory: 'train.csv'
Here's the absolute path for the .csv file and the python scripts.
import os
os.path.abspath("/Users/scdavis6/Desktop/train.csv")
'/Users/scdavis6/Desktop/train.csv'
import os
os.path.abspath("/Users/scdavis6/Documents/Kaggle/Titanic1.py")
'/Users/scdavis6/Documents/Kaggle/Titanic1.py'
Assuming that this is your actual code, the problem is that you never open the file. Your csv_file_object is still just the fileName, and thus your data is made up of the characters of that file name, resulting in a 1D numpy array.
Instead, you should open the file and create a csv.reader for it.
import csv
with open(fileName) as f:
reader = csv.reader(f)
data=[]
for row in reader:
data.append(row)
data = np.array(data)
Or shorter: data = np.array([row for row in csv.reader(f)])
Update: The new error you are getting is probably due to you accidentally changing
os.path.join('train.csv') to os.path('train.csv'), i.e., instead of calling the join function from the os.path module, you are (trying to) call the module itself.
Update: It seems your train.csv file is not in the same directory as your Python script, thus the script won't find the file if you just use the filename. You have to use the absolute path together with the filename:
fileName = os.path.join('/Users/scdavis6/Desktop', 'train.csv')
Or just fileName = '/Users/scdavis6/Desktop/train.csv'. Alternatively, move your train.csv file to the same directory as your Python script. This might indeed be the better and more robust option, unless you are using this file in multiple scripts in different directories.