Invalid filename or mode 'wb' - python

I am using django. I was trying to compress an icon uploaded by a user to a smaller size using Pythons Image library.
Following is my code:
def resizeImage(icon,ext):
path= os.path.join(settings.SITE_ROOT,'karnadash/static/tempfiles/temp'+ext)
destination = open(path,'wb+')
for chunk in icon.chunks():
destination.write(chunk)
destination.close()
image = Image.open(path)
image= image.resize((50, 50), Image.ANTIALIAS)
image.save(path)
return image
Problem is I am getting an internal server error. The last part of the stack trace is as follows:
line 31, in resizeImage
image.save(path)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1446, in save
fp = builtins.open(fp, "wb+")
IOError: [Errno 22] invalid mode ('wb') or filename: 'C:/Users/Silent/Documents/Python/karnadash/karnadash/static/tempfiles/temp.jpg'
Can anybody please explain why this is happening?

What solved it for me was switching from backslashes to forward slashes! Who would've thought?!
Similar post: ioerror invalid mode w

Check your file path if it's valid:
C:/Users/Silent/Documents/Python/karnadash/karnadash/static/tempfiles/temp.jpg
Perhaps it contains one karnadash too much.

I had a similar problem when I was trying to save some figures in a fowder. Some figures I could save, but couldn't save others, and I was using the same code. I realized that the name of the figure and the backslash were in conflict with a reserved code.
IOError: [Errno 22] invalid mode ('wb') or filename: '02102016\nDTG.png'
I think "\n" was interpreted as "enter". The problem had been solved when I changed it to forward slash.

Related

IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaaD:\\NLP\\cv082_11080.csv' in pycharm

This is my code in pycharm:
#coding=utf-8
import csv
path=r'‪D:\NLP\cv082_11080.csv'
with open(path) as f: # 采用b的方式处理可以省去很多问题
reader = csv.reader(f)
for row in reader:
print reader
But it always gives this error:
IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaaD:\NLP\cv082_11080.csv'
But when I run the code in the Python command line, it works well. So then I lool the setting in pycharm, but the option of file-encoding is right, the project and the IDE coding is both UTF-8.
How do I solve this?
You're getting an error because your path has some invisible characters in it (like the error message suggests):
IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaaD:\\NLP\\cv082_11080.csv' in pycharm
^^^^^^^^^^^^
Delete this entire line:
path=r'‪D:\NLP\cv082_11080.csv'
And type it out by hand again. You probably copy-pasted the path from somewhere and your text editor isn't showing the invisible character.
Those characters are the UTF-8 encoding of \u202a, which is a left-to-right mark.
问题出在编码造成的路径错误。
maybe first line code 没有起到作用
建议#coding=utf-8修改为
# coding:utf-8
注意 # 和 coding 之间有一个空格。

PyPDF2 IOError: [Errno 22] Invalid argument on PyPdfFileReader Python 2.7

Goal = Open file, encrypt file, write encrypted file.
Trying to use the PyPDF2 module to accomplish this. I have verified theat "input" is a file type object. I have researched this error and it translates to "file not found". I believe that it is linked somehow to the file/file path but am unsure how to debug or troubleshoot. and getting the following error:
Traceback (most recent call last):
File "CommissionSecurity.py", line 52, in <module>
inputStream = PyPDF2.PdfFileReader(input)
File "build\bdist.win-amd64\egg\PyPDF2\pdf.py", line 1065, in __init__
File "build\bdist.win-amd64\egg\PyPDF2\pdf.py", line 1660, in read
IOError: [Errno 22] Invalid argument
Below is the relevant code. I'm not sure how to correct this issue because I'm not really sure what the issue is. Any guidance is appreciated.
for ID in FileDict:
if ID in EmailDict :
path = "C:\\Apps\\CorVu\\DATA\\Reports\\AlliD\\Monthly Commission Reports\\Output\\pdcom1\\"
#print os.listdir(path)
file = os.path.join(path + FileDict[ID])
with open(file, 'rb') as input:
print type(input)
inputStream = PyPDF2.PdfFileReader(input)
output = PyPDF2.PdfFileWriter()
output = inputStream.encrypt(EmailDict[ID][1])
with open(file, 'wb') as outputStream:
output.write(outputStream)
else : continue
I think your problem might be caused by the fact that you use the same filename to both open and write to the file, opening it twice:
with open(file, 'rb') as input :
with open(file, 'wb') as outputStream :
The w mode will truncate the file, thus the second line truncates the input.
I'm not sure what you're intention is, because you can't really try to read from the (beginning) of the file, and at the same time overwrite it. Even if you try to write to the end of the file, you'll have to position the file pointer somewhere.
So create an extra output file that has a different name; you can always rename that output file to your input file after both files are closed, thus overwriting your input file.
Or you could first read the complete file into memory, then write to it:
with open(file, 'rb') as input:
inputStream = PyPDF2.PdfFileReader(input)
output = PyPDF2.PdfFileWriter()
output = input.encrypt(EmailDict[ID][1])
with open(file, 'wb') as outputStream:
output.write(outputStream)
Notes:
you assign inputStream, but never use it
you assign PdfFileWriter() to output, and then assign something else to output in the next line. Hence, you never used the result from the first output = line.
Please check carefully what you're doing, because it feels there are numerous other problems with your code.
Alternatively, here are some other tips that may help:
The documentation suggests that you can also use the filename as first argument to PdfFileReader:
stream – A File object or an object that supports the standard read
and seek methods similar to a File object. Could also be a string
representing a path to a PDF file.
So try:
inputStream = PyPDF2.PdfFileReader(file)
You can also try to set the strict argument to False:
strict (bool) – Determines whether user should be warned of all
problems and also causes some correctable problems to be fatal.
Defaults to True.
For example:
inputStream = PyPDF2.PdfFileReader(file, strict=False)
Using open(file, 'rb') was causing the issue becuase PdfFileReader() does that automagically. I just removed the with statement and that corrected the problem.
with open(file, 'rb') as input:
inputStream = PyPDF2.PdfFileReader(input)
This error raised up because of PDF file is empty.
My PDF file was empty that's why my error was raised up. So First of all i fill my PDF file with some data and Then start reeading it using PyPDF2.PdfFileReader,
And it solved my Problem!!!
Late but, you may be opening an invalid PDF file or an empty file that's named x.pdf and you think it's a PDF file

urllib2.urlopen to open download link

i am trying to download data from a site with this code
import urllib2
source = urllib2.urlopen("http://www.eia.gov/dnav/pet/hist/LeafHandler.ashx?n=PET&s=WRPUPUS2&f=W").read()
open("http://www.eia.gov/dnav/pet/hist/LeafHandler.ashx?n=PET&s=WRPUPUS2&f=W", "wb").write(source)
and keep getting the following error,
IOError: [Errno 22] invalid mode ('w') or filename: 'http://www.eia.gov/dnav/pet/hist/LeafHandler.ashx?n=PET&s=WRPUPUS2&f=W'
I am a little confused.
Python thinks / is directory so obviously that directory does not exist, it is also not valid using /'s in a filename on unix.
You could replace the / with another character like a .: and your code will run fine
with open("www.eia.gov.dnav.pet.hist.LeafHandler.ashx?n=PET&s=WRPUPUS2&f=W", "wb") as f:
f.write(source)

Python: Unable to open and read a file

I am totally new to python.
I was trying to read a file which I already created but getting the below error
File "C:/Python25/Test scripts/Readfile.py", line 1, in <module>
filename = open('C:\Python25\Test scripts\newfile','r')
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile
My code:
filename = open('C:\Python25\Test scripts\newfile','r')
print filename.read()
Also I tried
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
But same errors I am getting.
Try:
fpath = r'C:\Python25\Test scripts\newfile'
if not os.path.exists(fpath):
print 'File does not exist'
return
with open(fpath, 'r') as src:
src.read()
First you validate that file, that it exists.
Then you open it. With wrapper is more usefull, it closes your file, after you finish reading. So you will not stuck with many open descriptors.
I think you're probably having this issue because you didn't include the full filename.
You should try:
filename = open('C:\Python25\Test scripts\newfile.txt','r')
print filename.read()
*Also if you're running this python file in the same location as the target file your are opening, you don't need to give the full directory, you can just call:
filename = open(newfile.txt
I had the same problem. Here's how I got it right.
your code:
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
Try this:
with open('C:\\Python25\\Test scripts\\newfile') as myfile:
print(myfile.read())
Hope it helps.
I am using VS code. If I am not using dent it would not work for the print line. So try to have the format right then you will see the magic.
with open("mytest.txt") as myfile:
print(myfile.read())
or without format like this:
hellofile=open('mytest.txt', 'r')
print(hellofile.read())

os.path.join returning Errno22 in Enthought/Python

I'm working with a fairly complex Enthought/Python program that is returning this error:
File "C:\Users\riddle\Desktop\FCI2\src\equation.py", line 41, in main
fci_data = np.load(os.path.join(local_data_path, "fci_data.npy"))
File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 329, in load
fid = open(file, "rb")
IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\Users\white\\Desktop\
\FCI2New\\data\\fci_data.npy'
With respect to this:
fci_data = np.load(os.path.join(local_data_path, "fci_data.npy"))
fci_data = fci_data.replace("'\\','/'")
The additional slashes are particularly puzzling me. local_data_path is global and is defined like so:
local_data_path = static.base_data_path
base_data_path = "C:\Documents and Settings\white\Desktop\FCI2New\data" (from the static module)
Anyone have an idea what might be the issue here? 'rb' should be the correct mode for fci_data. Please forgive any errors or obvious questions, I'm a beginner.
Anne
try first to normalize the path :
local_data_path = os.path.normpath(local_data_path)

Categories

Resources