Linux os : Sending email using multiple attachment using python [closed] - linux

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Could someone please help me with the below requirement. I am using below version of linux os :-
Red Hat Enterprise Linux Server release 6.6 (Santiago)
Python version :2.6.6
I need to send a multiple log files to an user everyday as an attachment.
In my log directory i have multiple files with *.fix extension. I need to send all these files to user as attachment. Could you please let me know the code for it ?
FYI .. its a linux server and i am not gonna use gmail.
Appreciate your earliest help. Thanks !!

There is a python package called email that helps you in sending mails.
Getting the list of *.fix files could be done using glob.
Something like this should do it:
from glob import glob
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
# Fill out the needed properties of msg, like from, to, etc.
for filename in glob("*.fix"):
fp = open(filename)
msg.attach(MIMEText(fp.read()))
fp.close()
...
The msgcan then be sent using smtplib as shown here

Related

Unzip all the items from the output of rglob() method using pathlib module [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a folder that contains zip files in subfolders. I want to unzip all the files using this python code. code shows no error but the files are not extracted can't figure out the problem. Thanks in Advance.
from zipfile import ZipFile
from pathlib import Path
entries = Path('E:\\Bootcamp')
for entry in entries.rglob('*.zip'):
with ZipFile(entry, 'r') as zip:
print('Check1')
zip.extractall()
print('check2')
The extracted files will be located in the folder where your python file has been saved

How to login a site using Python 3.7? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to write a code in python 3.7 that login a site.
For example, When I get username and password, the code should do the login process to the site.
I'm unsure of what you mean, if you're logging into a site or trying to process a login request, but I'm going to assume the former.
There's one way using Selenium. You can inspect element the site to find the id's for the input for username/password, then use the driver to send the information to those inputs.
Example:
from selenium import webdriver
username = "SITE_ACCOUNT_USERNAME"
password = "SITE_ACCOUNT_PASSWORD"
driver = webdriver.Chrome("path-to-driver")
driver.get("https://www.facebook.com/")
username_box = driver.find_element_by_id("email")
username_box.send_keys(username)
password_box = driver.find_element_by_id("pass")
password_box.send_keys(password)
try:
login_button = driver.find_element_by_id("u_0_8")
login_button.submit()
except Exception as e:
login_button = driver.find_element_by_id("u_0_2")
login_button.submit()
This logs into facebook using the chromedriver.

Create a new csv file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm using python and am trying to create a new csv file using the csv module (i.e. one that doesn't currently exist). Does anyone know how to do this?
Thanks in advance,
Max
if you want simply create a csv file you can use built in method open, for more about open check this
with open("filename.csv","a+") as f:
f.write(...)
or if you want to read an exist csv file you can use this
import csv
with open('filename.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in
print ', '.join(row)
#if you want to save the file into given path
import os
os.rename("filename.csv","path/to/new/desination/for/filename.csv")
for more check docs

(PYTHON) Manipulating certain portions of URL at user's request [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
The download link I want to manipulate is below:
http://hfrnet.ucsd.edu/thredds/ncss/grid/HFR/USWC/6km/hourly/RTV/HFRADAR,_US_West_Coast,_6km_Resolution,_Hourly_RTV_best.ncd?var=u&var=v&north=47.20&west=-126.3600&east=-123.8055&south=37.2500&horizStride=1&time_start=2015-11-01T00%3A00%3A00Z&time_end=2015-11-03T14%3A00%3A00Z&timeStride=1&addLatLon=true&accept=netcdf
I want to make anything that's in bold a variable, so I can ask the user what coordinates and data set they want. This way I can download different data sets by using this script. I would also like to use the same variables to name the new file that was downloaded ex:USWC6km20151101-20151103.
I did some research and learned that I can use the urllib.parse and urllib2, but when I try experimenting with them, it says "no module named urllib.parse."
I can use the webbrowser.open() to download the file, but manipulating the url is giving me problems
THANK YOU!!
Instead of urllib you can use requests module that makes downloading content much easier. The part that makes actual work is just 4 lines long.
# first install this module
import requests
# parameters to change
location = {
'part': 'USWC',
'part2': '_US_West_Coast',
'km': '6km',
'north': '45.0000',
'west': '-120.0000',
'east': '-119.5000',
'south': '44.5000',
'start': '2016-10-01',
'end': '2016-10-02'
}
# this is template for .format() method to generate links (very naive method)
link_template = "http://hfrnet.ucsd.edu/thredds/ncss/grid/HFR/{part}/{km}/hourly/RTV/\
HFRADAR,{part2},_{km}_Resolution,_Hourly_RTV_best.ncd?var=u&var=v&\
north={north}&west={west}&east={east}&south={south}&horizStride=1&\
time_start={start}T00:00:00Z&time_end={end}T16:00:00Z&timeStride=1&addLatLon=true&accept=netcdf"
# some debug info
link = link_template.format(**location)
file_name = location['part'] + location['km'] + location['start'].replace('-', '') + '-' + location['end'].replace('-', '')
print("Link: ", link)
print("Filename: ", file_name)
# try to open webpage
response = requests.get(link)
if response.ok:
# open file for writing in binary mode
with open(file_name, mode='wb') as file_out:
# write response to file
file_out.write(response.content)
Probably the next step would be running this in loop on list that contains location dicts. Or maybe reading locations from csv file.

Best tool for text extraction from PDF in Python 3.4 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I am using Python 3.4 and need to extract all the text from a PDF and then use it for text processing.
All the answers I have seen suggest options for Python 2.7.
I need something in Python 3.4.
Bonson
You need to install the PyPDF2 package to be able to work with PDFs in Python. PyPDF2 can extract text/images. The text is returned as a Python string. To install it, run pip install PyPDF2 from the command line. This module name is case-sensitive so make sure to type 'y' in lowercase and all other characters as uppercase.
import PyPDF2
reader = PyPDF2.PdfReader('my_file.pdf')
print(len(reader.pages)) # gives '56'
page = reader.pages[9] #'9' is the page number
page.extract_text()
The last statement returns all the text that is available in page 9 of 'my_file.pdf' document.
pdfminer.six ( https://github.com/pdfminer/pdfminer.six ) has also been recommended elsewhere and is intended to support Python 3. I can't personally vouch for it though, since it failed during installation MacOS. (There's an open issue for that and it seems to be a recent problem, so there might be a quick fix.)
Complementing #Sarah's answer. PDFMiner is a pretty good choice. I have been using it from quite some time, and until now it works pretty good on extracting the text content from a PDF. What I did is to create a function which uses the CLI client from pdfminer, and then it saves the output into a variable (which I can use later on somewhere else). The Python version I am using is 3.6, and the function works pretty good and does the required job, so maybe this can work for you:
def pdf_to_text(filepath):
print('Getting text content for {}...'.format(filepath))
process = subprocess.Popen(['pdf2txt.py', filepath], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
if process.returncode != 0 or stderr:
raise OSError('Executing the command for {} caused an error:\nCode: {}\nOutput: {}\nError: {}'.format(filepath, process.returncode, stdout, stderr))
return stdout.decode('utf-8')
You will have to import the subprocess module of course: import subprocess
slate3k is good for extracting text. I've tested it with a few PDF files using Python 3.7.3, and it's a lot more accurate than PyPDF2, for instance. It's a fork of slate, which is a wrapper for PDFMiner. Here's the code I am using:
import slate3k as slate
with open('Sample.pdf', 'rb') as f:
doc = slate.PDF(f)
doc
#prints the full document as a list of strings
#each element of the list is a page in the document
doc[0]
#prints the first page of the document
Credit to this comment on GitHub:
https://github.com/mstamy2/PyPDF2/issues/437#issuecomment-400491342
import pdfreader
pdfFileObj = open('/tmp/Test-test-test.pdf','rb')
viewer = SimplePDFViewer(pdfFileObject)
viewer.navigate(1)
viewer.render()
viewer.canvas.strings

Resources