UTF-8 error with the python open() function - python-2.7

I wrote a simple code in python the only opens and read a file
def read_text():
quotes = open("‪C:/Users/Matteo/Desktop/quotes.txt")
contents_of_file = quotes.read()
print(contents_of_file)
quotes.close()
read_text()
When i try to execute it this is what appears
Traceback (most recent call last):
File "C:\Python27\read.py", line 6, in <module>
read_text()
File "C:\Python27\read.py", line 2, in read_text
quotes = open("‪C:/Users/Matteo/Desktop/quotes.txt")
IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaaC:/Users /Matteo/Desktop/quotes.txt'
Searching on the internet i understood that the problem is that IDLE recognizes an Unicode character before C, \xe2\x80\xaa, that is a "LEFT-TO-RIGHT EMBEDDING". I have no idea of what is this and how to remove from my code.

Your code contains an invisible character (probably because you copy/pasted the filename from somewhere). Try deleting the "C: part and retyping it.

Related

Accessing a csv file in python

I keep getting an "invalid keyword" error when i try to read from a csv file in python. Any ideas for a work around for this?
C:\Python27\python.exe C:/Users/User_Name/PycharmProjects/untitled/car.py
Traceback (most recent call last): File
"C:/Users/User_Name/PycharmProjects/untitled/car.py", line 122, in <module> d = handle_refugee_data.DataTable(csvformat="generic", data_directory="car2014", start_date="2013-12-01") File
"C:\Users\User_Name\PycharmProjects\untitled\handle_refugee_data.py", line 78, in __init__ with open("%s/%s" % (data_directory, data_layout), newline='') as csvfile:
TypeError: 'newline' is an invalid keyword argument for this function
Process finished with exit code 1
========================================================================
newline is a valid keyword argument to open() in Python 3, but not in Python 2, which appears to be what you are using.
One solution, if possible, would be to execute the script with Python 3 instead. Alternatively, as pointed out by #dhke in the comments, you could use io.open() instead, which does accept a newline keyword argument.
Of course, you could probably use the csv module instead, depending on your use case (which is not clear from the original question).

Printing a tuple instead of text

x= input('What is your name? ')
print('Heloo',x)
The above code is giving an output ('Heloo', 5) for the input as 5.
The above code is giving an output ('Heloo', 'shubham') for the input as 'shubham'.
The above code is giving an error for the input as shubham without quotes.
Traceback (most recent call last):
File "C:/Users/SHUBHAM/Desktop/Python1.py", line 1, in <module>
x= input('What is your name? ')
File "<string>", line 1, in <module>
NameError: name 'shubham' is not defined
Can anyone suggest me what is the error with my code?
Thank You.
shubham is not defined. It works for x because you are asking the user to define x, which is why when you call on it to print it works. It works in quotes because you are telling Python that it is a string but when you leave it without quotes it assumes it is a variable, but since you have not assigned anything to it, it gives you this error.

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

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.

encoding errors when replacing unwanted characters in utf-8 encoded file

Code can be downloaded here:
https://github.com/kelrien/pyretrieval/
whenever I execute my example.py, the following error pops up:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "example.py", line 21, in <module>
docs.append(proc.process(line.decode("utf-8")))
File "pyretrieval\processor.py", line 61, in process
tokens = self.tokenize(string)
File "pyretrieval\processor.py", line 47, in tokenize
temp = temp.replace(char, self.replace_characters[char])
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 0: ordinal not in range(128)
As you can see - the error happens when trying to replace german umlauts I specified. If I don't use the replace_characters dict and just ignore those umlauts, I'm not getting the error.
I already tried a lot of stuff:
Using the codecs module
Using encode("utf-8") and decode("utf-8") at different
I found a solution. I had to encode the characters I wanted to replace in unicode too(in processor.py).
I already pushed the necessary changes to github. https://github.com/kelrien/pyretrieval