If you were to save an Image using it's URL how would you do it ?
Also how do I give the Image a unique file name while saving it.
response = urllib.urlopen(image_url)
file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
f = open('/media/images/temp/'+file_name, "wb")
f.write(response.read())
f.close()
It throws no error nor saves the file... I'm new to this I have no clue what is going wrong : |
import urllib
import string
import random
import os
filename_charset = string.ascii_letters + string.digits
filename_length = 10
file_save_dir = '/home/user/download/'
filename = ''.join(random.choice(filename_charset)
for s in range(filename_length))
urllib.urlretrieve ("http://www.example.com/image.png",
os.path.join(file_save_dir, filename + '.png'))
Related
I have a function that asks the user for a PDF file and receive the page number the user wish to convert into an image. The function usually works fine however with a few PDFs it does not work, the image that is returned is blank and it has 4 mega bytes. Apparently it has something to do with the size of the file. Is there a way to solve this problem?
from PyPDF2 import PdfFileReader, PdfFileWriter
from tkinter.filedialog import askopenfilename
from pdf2image import convert_from_path
import os
import PIL
PIL.Image.MAX_IMAGE_PIXELS = None
def convert_pdf(page_number):
filename = askopenfilename()
pdf_file_path = filename
file_base_name = pdf_file_path.replace('.pdf', '')
pdf = PdfFileReader(pdf_file_path)
pages = [page_number]
pdfWriter = PdfFileWriter()
for page_num in pages:
pdfWriter.addPage(pdf.getPage(page_num))
with open('{0}_subset.pdf'.format(file_base_name[:-5]), 'wb') as f:
pdfWriter.write(f)
f.close()
n = file_base_name[:-5]
nome = f'{n}_subset.pdf'
pages = convert_from_path(nome, poppler_path=r'C:\Program Files\poppler-0.68.0\bin')
i = 1
name = os.path.basename(nome).split('/')[-1][:-4]
for page in pages:
image_name = "Page_" + str(i) + f"{name}.jpg"
page.save(image_name, "JPEG")
i = i + 1
The solution to this problem was to change the DPI parameter of convert_from_path function. It is important to leave the DPI as it is, since I found that certain images become really small, and therefore unreadable.
try:
pages = convert_from_path(nome, poppler_path=r'C:\Program Files\poppler-0.68.0\bin')
i = 1
except:
PIL.Image.MAX_IMAGE_PIXELS = None
pages = convert_from_path(nome, 25,poppler_path=r'C:\Program Files\poppler-0.68.0\bin')
i = 1
I basically used requests and now I have links to webpages which have images on them. I want to extract just the images and make a file where I store them for later viewing. How would I do so?
import requests
import string
import random
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
for i in range(50):
link = id_generator()
print("https://prnt.sc/" + link)
r = requests.get("https://prnt.sc/" + link)
response = requests.get("https://i.imgur.com/ExdKOOz.png")
file = open("sample_image.png", "wb")
file.write(response.content)
file.close()
I would like to save a JSON file from the variable 'data' through an API.
I've created a function writetoJsonfile to do it but it does not work.
Can you guys help me out? Thank you.
import requests,json,io
import xmltodict
import logging as log
import pandas as pd
from io import BytesIO
from zipfile import ZipFile
from datetime import datetime
def writeToJSONFile(path, filename, cs ):
path = 'C:/Users/Skelaton/Desktop'
filename = 'compromised_systems'
ext = 'json'
filePathNameWExt = path + filename + ext
with open(filePathNameWExt, 'w') as fp :
json.dump(cs, fp)
def getdata(person_id):
log.info("Downloading all data from people {}".format(person_id))
payload = {'format' : 'csv'}
r = requests.get
("https://example.com/people/{}/reports/person".format(person_id),
auth=(api_key,''), proxies=proxy,params=payload)
if r.status_code == 200:
data = pd.read_csv(BytesIO(r.content),error_bad_lines=False)
data = data.to_json(orient="records")
data = json.loads(data)
return data
else:
log.error("Unable to download all data due to status code :
{}".format(r.status_code))
return False
Your file path doesn't seem right.
This works:
path = 'C:/Users/Skelaton/Desktop/'
filename = 'compromised_systems'
ext = '.json'
filePathNameWExt = path + filename + ext
def write_to_file(filename, data):
with open(filename, 'w+') as fp:
fp.write(json.dumps(data))
I would like to use a python script to find and replace some text in an InDesign file and then save it as pdf.
I managed to use python to open indesign and save it as pdf however I do not know how to search for text and replace it with a random string generated by the first part of the script.
Here is what I got so far:
import win32com.client
import random
import string
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
voucher=id_generator()
app = win32com.client.Dispatch('InDesign.Application.CC.2018')
myFile = r'C:\Users\some_file.indd'
myDocument = app.Open(myFile)
myPDFFile = r'C:\Users\some_file.pdf'
directory = os.path.dirname(myPDFFile)
idPDFType = 1952403524
# 1=[High Quality Print], 2=[PDF/X-1a:2001] etc..
myPDFPreset = app.PDFExportPresets.Item(1)
try:
if not os.path.exists(directory):
os.makedirs(directory)
if os.path.exists(directory):
myDocument.Export(idPDFType, myPDFFile, False, myPDFPreset)
except Exception as e:
print('Export to PDF failed: ' + str(e))
myDocument.Close()
You need to iterate over all of the TextFrames of the document and then search and replace the text with the ChangeText function.
Here is a snippet of what you can do:
voucher = id_generator()
searchText = 'test'
app = win32com.client.Dispatch('InDesign.Application.CC.2018')
app.scriptPreferences.userInteractionLevel = 1699640946
myFile = r'C:\Users\some_file.indd'
myDocument = app.Open(myFile)
myPage = myDocument.Pages.Item(1)
idNothing = 1851876449 #from enum idNothingEnum, see doc_reference
for it in myDocument.TextFrames:
if searchText in (it.Contents):
app.FindTextPreferences.FindWhat = searchText
app.ChangeTextPreferences.ChangeTo = voucher
it.ChangeText()
continue
app.FindTextPreferences.FindWhat = idNothing
app.ChangeTextPreferences.ChangeTo = idNothing
#and then save the changes as PDF...
I'm trying to loop through a list of ~3,000 URLs and create QR codes for them. In one column I have the URLs and in another column I have what I want the QR code file names to be named when output as images.
The problem is the URLs that get converted to QR codes and my file names both come out encased in brackets.
For example:
URL Filename
www.abel.com Abel
Comes out as:
URL in QR Code Filename of QR Code
[www.abel.com] [Abel]
Here's my code so far:
import csv
import qrcode
import pandas as pd
df = pd.read_csv('QR_Python_Test.csv')
i = 1
x = df.iloc[[i]]
print(
x.QR_Code_Name.values)
for i in df.index:
z = df.iloc[[i]]
x = str(z.Link_Short.values)
qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=5,border=2,)
qr.add_data(x)
qr.make(fit=True)
img = qr.make_image()
file_name = str(z.QR_Code_Name.values) + ".png"
print('Saving %s' % file_name)
image_file = open(file_name, "w")
img.save(file_name)
image_file.close()
file.close()
And some sample data:
URL Filename
www.apple.com Apple
www.google.com Google
www.microsoft.com Microsoft
www.linux.org Linux
Thank you for your help,
Me
If your DataFrame contains the correct information, you can use DataFrame.itertuples
also separate the functions
reading the data from the file
generating the qr-code
saving the files
That way, you can test each of these individually
def generate_images(df):
for row in df.itertuples():
yield row.Filename, generate_qr(row.URL)
def generate_qr(url):
qr = qrcode.QRCode(version=5, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=5,border=2,)
qr.add_data(url)
qr.make(fit=True)
return qr.make_image()
def save_qr_code(qr_codes):
for filename, qr_code in qr_codes:
filename = filename + '.png'
print('saving to file %s' % (filename,)
with open(filename, 'wb') as file:
qr_code.save(file)
df = pd.read_csv('my_data.csv')
qr_codes = generate_images(df)
save_qr_code(qr_codes)