Displaying pdf file in cgi with python 3.6 - python-3.x

The following code works fine to display a pdf file with python 3.2. However with python 3.6 it doesn't (the browser gives a 'Failed to load PDF document' error). I think this is because the byte string returned by read() in 3.6 prints with a leading b' and trailing '.
Can anyone tell me how to do this in 3.6? Thank you.
#!/usr/bin/python
with open('sol.pdf', 'rb') as fp:
print("Content-type: application/pdf\n")
print(fp.read())

The following should work:
with open('sol.pdf', 'rb') as fp:
print("Content-type: application/pdf\n")
sys.stdout.flush()
sys.stdout.buffer.write(fp.read())
The sys.stdout.flush needs to appear before the sys.stdout.buffer.write to ensure that the headers appear first.

Related

Can't open and import files on Python

I just started learning Python this month with no prior coding knowledge. Before I could even get to practice coding, I was stuck with opening & importing files! To this end, I have no idea how to fix the problems as a newbie, so I will try to explain as best as I can.
1. Opening files.
Working directory is correct. The csv file was created with Geany on the Ubuntu operating system.
name=[]
age=[]
height=[]
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
csv file:
reader = csv.reader(csvfile, delimiter=’,’)
for row in reader:
name.append(row[0])
age.append(row[1])
height.append(row[2])
print("Done!")
**Error message:**
File "<ipython-input-3-f801fef0d65e>", line 5
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
^
SyntaxError: invalid character in identifier
2. Importing files
I downloaded a whatsapp chat text file for a coding exercise. It is stored in my Desktop environment. However, when I attempted to import it on Jupyter Notbook it didn't work.
I believe this is the problem, although I do not know how to work-around this:
the txt file's location as shown in my terminal:
/Users/Mac/Desktop
while the working directory as shown on Jupyter is:
/home/stephanie/Desktop
with open ("_chat.txt") as f:
data = f.readlines()
**error message:**
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-5-07cb5c381c47> in <module>
----> 1 with open ("_chat.txt") as f:
2 data = f.readlines()
FileNotFoundError: [Errno 2] No such file or directory: '_chat.txt'```
Any input or advice is greatly appreciated. Thanks very much in advance!
For the first error, try changing the apostrophes in the open line. For example, change ’/home/stephanie/chapter5exercise.csv’ to '/home/stephanie/chapter5exercise.csv'.
Apparently, the apostrophe (’) that you are using is not the correct one.
For the second error, try giving the entire path of the txt file.

ModuleNotFoundError: No module named 'numpy.core.multiarray\r'

I am trying to load a pkl file,
pkl_file = open(sys.argv[1], 'rb')
world = pickle.load(pkl_file)
but I get an error from these lines
Traceback (most recent call last):
File "E:/python/test.py", line 186, in <module>
world = pickle.load(pkl_file)
ModuleNotFoundError: No module named 'numpy.core.multiarray\r'
I am using Windows 10, python 3.7, and installed four packages (numpy 1.17.2, opencv-python 4.1.1.26, pip 19.2.3, setuptools 41.2.0 ). I have tried to change "rb" to "r", but still got the error, how can I fix this?
I think there are two problems here.
First, your pickle is or contains a NumPy object, which is not part of the standard library. Therefore you must ensure that NumPy is installed into your current Python environment and imported before you try to load the pickled object. Depending on your setup, installation may be as simple as,
pip install numpy
Then you must add the line,
import numpy as np
to the top of your script.
Second, it looks like Python is encountering this issue, where your binary file was erroneously saved as text on Windows, resulting in resulted in each '\n' being converted to '\r\n'. To fix this, you must re-convert to '\r\n' back to '\n'. So long as the file isn't huge, this usually isn't very painful.
Here is a relatively complete example:
import sys
import numpy as np
src = sys.argv[1] # path to your file
data = open(src).read().replace('\r\n', '\n') # read and replace file contents
dst = src + ".tmp"
open(dst, "w").write(data) # save a temporary file
world = pickle.load(open(dst, "rb"), encoding='latin1')
Ok, I just had to figure this out for myself, and I solved it. All you have to do is change all the "\r\n" to "\n". You can do this in multiple ways. You can go into Notepad++ and change line endings from CR LF to just LF. Or programmatically you can do
open(newfile, 'w', newline = '\n').write(open(oldfile, 'r').read())

Get a table from a website to a CSV file

I need to transform the tables from a website to a CSV file.
I am using Python 3 from a raspberryPi.
Here is the code that I am using:
from urllib.request import urlopen, Request, URLError
from TableParser import TableParser
url_addr ='http://www.tbs-sct.gc.ca/pses-saff/2017-2/results-resultats/bq-pq/12/org-eng.aspx#s1'
req = Request(url_addr)
url = urlopen(req)
tp = TableParser()
tp.feed(url.read())
#Here I want the first table
my_table = tp.get_tables()[0]
filename = 'table_as_csv.csv'
f = open(filename, 'wb')
with f:
writer = csv.writer(f)
for row in table:
writer.writerow(row)
When I try to run it, I get:
ImportError: No module named 'TableParser'.
I am new to Python and I don't know what to do. Any help would be very appreciated.
Thanks!
First off, I think you should familiarise yourself with python and its syntax as well as how it handles errors. Clearly you want to do something quick and be done with it. Here's a simple python tutorial
To answer your question
ImportError exceptions occur when you do not have that particular module installed using pip installation preferrably. Until it is installed your script wont run successfully.
The error means TableParser has not been installed yet and you could do this by
pip3 install TableParser
This assumes you know where the module is and can be installed using pip
I see you are using the module csv but have not imported it as well. You should.

Unicode character causing error with bdist_wininst on python 3 but not python 2

I'm compiling windows installers for my python code. I mostly write language-related tools and include examples that require utf-8 strings in my documentation, including the README file.
I'm slowly moving from Python 2 to Python 3 and recently found that the command
python setup.py bdist_wininst
works fine with python 2 but not for python 3.
I've traced the problem to the inclusion of unicode in my readme file. The readme file gets read into setup.py.
The bug occurs in Python36\lib\distutils\command\bdist_wininst.py
The error is:
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character
In python 2.7 the relevant code in bdist_wininst.py is
if isinstance(cfgdata, str):
cfgdata = cfgdata.encode("mbcs")
In python 3.6 the equivalent code in bdist_wininst.py is
try:
unicode
except NameError:
pass
else:
if isinstance(cfgdata, unicode):
cfgdata = cfgdata.encode("mbcs")
Here is my readme file:
https://github.com/timmahrt/pysle/blob/master/README.rst
And here is my setup.py file that reads in the README file
https://github.com/timmahrt/pysle/blob/master/setup.py
And the relevant line from setup.py:
long_description=codecs.open('README.rst', 'r', encoding="utf-8").read()
My question:
Is there a way to make python 3 happy in this case?

Read csv file Anaconda | Python 3

I am trying to open a CSV file on Anaconda (Python 3) unsuccessfully.
I tried with a raw string, I included the whole path and also tried with the double backslashes but nothing worked. I still get the Errno 2 No such file or directory.
This is my code:
reader = csv.reader(open(r'C:\Users\Marco\Desktop\trainingset.csv', newline=''), delimiter=' ', quotechar='|')
for row in reader:
print(", ",join(row))
I have the same issue when trying to open a csv file this way... I don't know the reason but instead, I use the pandas library that has a method named read_csv()
pandas.read_csv('myfile.csv')
It gets the content of your csv file as a dataframe object. This works with Python 3.5 using Anaconda3.

Resources