CSVをpandasで読もうとしたらエラー:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0x8f in position 0: invalid start byte

CSVをpandasで読もうとしたら

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0x8f in position 0: invalid start byte

というエラーになりました。エクセルファイルを開く分には問題なさそうなので、CSVでなくエクセルで処理しようと思います。

エクセルをpandasで読もうとしたらエラー ValueError: Max value is 14 

エクセルファイルをpandasで読もうとしたら、

ValueError: Max value is 14

というエラーになりました。これは一体何でしょうか。

  1. Openpyxl: ‘ValueError: Max value is 14’ when using load_workbook

自分で過去に同じエラーに遭遇して、付け焼刃的に解決していました。

  1. 【解決】ValueError: Max value is 14 pythonでエクセルを開こうとして出たエラー

目に見えない余計なものを除去するために、一度CSVで保存して、それをエクセルで保存しなおしたら直るようです。

pygameモジュールをインストールしようとしたらエラーメッセージfailed with initial frozen solve. Retrying with flexible solve.

UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

– pygame -> python[version=’2.7.*|3.5.*’]

Your python: python=3.7

If python is on the left-most side of the chain, that’s the version you’ve asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

という説明がありました。pygameはpython3.7には対応していないようです。

Anaconda NavigatorでCreateで新しい環境Environmentを作ることにします。ここでpyton3.5を指定。この環境にpython35と名付けておきます。で、jupyterをインストールするところから。結構時間がかかりますね。

で、jupyterノートブック上で、

!conda install -c cogsci pygame

を実行してみます。

うまくいきませんでした。状況はむしろ悪化して、普通にjupyterをつかうことすらできなくなりました。カーネルエラーというのになります。こまった。。

あれこれためして(Environmentsで使っていないものを削除したり)、base(root), Anaconda3, python35の3つの環境にまで減らしておいてpython35でjupyterノートブックを開き、そのノート上で、

!pip install -U pygame –user

としてRUNしました。すると、

  Downloading pygame-2.5.2-cp37-cp37m-win_amd64.whl (10.7 MB)
Installing collected packages: pygame
Successfully installed pygame-2.5.2

ぶじ終了のメッセージがでました。さっきと何が違ったのかわかりませんが。

 

 

 

pythonをつかってアクロバットでPDFを開いて、保存するスクリプト

pythonのスクリプト内からアクロバットを使ってPDFを開き、再保存する方法

give me a python code that automatically open pdf files in acrobat then save again in acrobat.

https://chat.openai.com/

Certainly! Here’s a Python code snippet that uses the subprocess module to open PDF files in Adobe Acrobat and save them again:

import subprocess

def open_pdf_and_save(filepath):
# Specify the path to your Adobe Acrobat executable
acrobat_path = r’C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe’

# Open the PDF file in Adobe Acrobat
subprocess.Popen([acrobat_path, filepath])

# Wait for Adobe Acrobat to open
input(“Press Enter after saving the PDF in Adobe Acrobat:”)

# Close Adobe Acrobat
subprocess.call([‘taskkill’, ‘/F’, ‘/IM’, ‘Acrobat.exe’])

# Usage example
pdf_filepath = r’C:\path\to\your\pdf\file.pdf’
open_pdf_and_save(pdf_filepath)

In this code, you need to provide the path to your Adobe Acrobat executable in the acrobat_path variable. Update the pdf_filepath variable with the path to your PDF file.

When you run the code, it will open the specified PDF file in Adobe Acrobat. After making any desired changes and saving the file in Adobe Acrobat, press Enter in the terminal to continue the Python script. The script will then close Adobe Acrobat.

Note: Make sure to replace C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe with the actual path to your Adobe Acrobat executable. The path may vary depending on the version and installation location of Adobe Acrobat on your system.

アドビアクロバットの場所の見つけ方

How can tell the path to my Adobe Acrobat executable in the acrobat_path variable in python language?

To find the path to your Adobe Acrobat executable programmatically in Python, you can utilize the winreg module to access the Windows registry. Here’s an example code snippet that retrieves the path to Adobe Acrobat:

import winreg

def get_acrobat_path():
acrobat_key_path = r”SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Acrobat.exe”

try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, acrobat_key_path) as key:
acrobat_path = winreg.QueryValue(key, None)
return acrobat_path
except FileNotFoundError:
return None

# Usage example
acrobat_path = get_acrobat_path()
if acrobat_path:
print(“Adobe Acrobat path:”, acrobat_path)
else:
print(“Adobe Acrobat is not installed or path not found.”)

This code uses the winreg.OpenKey() function to open the registry key for Adobe Acrobat (SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Acrobat.exe). If the key is found, it retrieves the default value, which represents the path to the Adobe Acrobat executable.

The get_acrobat_path() function returns the Adobe Acrobat path if found, or None if Adobe Acrobat is not installed or the path is not found.

You can then assign the returned acrobat_path to the acrobat_path variable in your code snippet.

 

フォルダ内の全てのPDFファイルに同様の処理をする方法

give me a python code that use adobe acrobat to open PDF fiels in a folder and resave each.

Certainly! Here’s a Python code snippet that uses Adobe Acrobat to open PDF files in a folder and resave each file:

import os
import subprocess

def open_pdf_and_resave(pdf_filepath):
# Specify the path to your Adobe Acrobat executable
acrobat_path = r’C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe’

# Open the PDF file in Adobe Acrobat
subprocess.Popen([acrobat_path, pdf_filepath])

# Wait for Adobe Acrobat to open
input(“Press Enter after resaving the PDF in Adobe Acrobat:”)

# Close Adobe Acrobat
subprocess.call([‘taskkill’, ‘/F’, ‘/IM’, ‘Acrobat.exe’])

def open_and_resave_pdfs_in_folder(folder_path):
# Get all PDF files in the folder
pdf_files = [file for file in os.listdir(folder_path) if file.endswith(‘.pdf’)]

# Iterate over each PDF file and open/resave it in Adobe Acrobat
for pdf_file in pdf_files:
pdf_filepath = os.path.join(folder_path, pdf_file)
open_pdf_and_resave(pdf_filepath)

# Usage example
folder_path = r’C:\path\to\your\folder\containing\pdfs’
open_and_resave_pdfs_in_folder(folder_path)

In this code, you need to provide the path to your Adobe Acrobat executable in the acrobat_path variable. Update the folder_path variable with the path to the folder containing the PDF files you want to open and resave.

When you run the code, it will iterate over each PDF file in the specified folder. It will open each file in Adobe Acrobat, allowing you to make any desired changes or modifications. After resaving the PDF file in Adobe Acrobat, press Enter in the terminal to continue the Python script. The script will then close Adobe Acrobat and proceed to the next PDF file in the folder.

Note: Make sure to replace C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe with the actual path to your Adobe Acrobat executable. The path may vary depending on the version and installation location of Adobe Acrobat on your system.

再保存まで自動でやる方法

give me a python code that use adobe acrobat to open PDF fiels in a folder and resave each also automatically in python without any human hands.

import os
import subprocess
import time
import pyautogui

def open_pdf_and_resave(pdf_filepath):
# Specify the path to your Adobe Acrobat executable
acrobat_path = r’C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe’

# Open the PDF file in Adobe Acrobat
subprocess.Popen([acrobat_path, pdf_filepath])

# Wait for Adobe Acrobat to open
time.sleep(5) # Adjust the sleep duration as needed

# Use PyAutoGUI to automate the resave process
pyautogui.hotkey(‘ctrl’, ‘shift’, ‘s’)
time.sleep(1)
pyautogui.press(‘enter’)

# Wait for the resave to complete
time.sleep(2)

# Close Adobe Acrobat
pyautogui.hotkey(‘ctrl’, ‘w’)

def open_and_resave_pdfs_in_folder(folder_path):
# Get all PDF files in the folder
pdf_files = [file for file in os.listdir(folder_path) if file.endswith(‘.pdf’)]

# Iterate over each PDF file and open/resave it in Adobe Acrobat
for pdf_file in pdf_files:
pdf_filepath = os.path.join(folder_path, pdf_file)
open_pdf_and_resave(pdf_filepath)

# Usage example
folder_path = r’C:\path\to\your\folder\containing\pdfs’
open_and_resave_pdfs_in_folder(folder_path)

In this code, you need to provide the path to your Adobe Acrobat executable in the acrobat_path variable. Update the folder_path variable with the path to the folder containing the PDF files you want to open and resave.

When you run the code, it will iterate over each PDF file in the specified folder. It will open each file in Adobe Acrobat using the subprocess module and then use PyAutoGUI to automate the resave process. The code simulates the keyboard shortcuts (Ctrl+Shift+S to save, Enter to confirm, and Ctrl+W to close) using the pyautogui library. Adjust the time.sleep() durations as needed to ensure proper timing for each action.

Please note that GUI automation can be sensitive to screen resolutions, window positions, and other factors. Make sure that your screen is set up appropriately and that Adobe Acrobat is visible and in focus when running the code. Additionally, exercise caution when automating GUI interactions and ensure that you have appropriate permissions for the files and applications involved.

ModuleNotFoundError: No module named ‘selenium’ seleniumモジュールのインストール方法

ModuleNotFoundError: No module named ‘selenium’

以前、seleniumを使ったスクリプトを使っていたのですが、久しぶりにそのスクリプトを実行しようとしたところ、

ModuleNotFoundError: No module named 'selenium'

というエラーが出てしまいました。なんでなくなったのかよくわかりませんが、再度モジュールをインストールする必要がありそうです。jupyternotebookの中で、

pip install selenium

として実行したら、

Collecting selenium
  Downloading selenium-4.8.0-py3-none-any.whl (6.3 MB)Note: you may need to restart the kernel to use updated packages.

Collecting trio~=0.17
  Downloading trio-0.22.0-py3-none-any.whl (384 kB)
Requirement already satisfied: certifi>=2021.10.8 in c:\programdata\anaconda3\lib\site-packages (from selenium) (2021.10.8)
Requirement already satisfied: urllib3[socks]~=1.26 in c:\programdata\anaconda3\lib\site-packages (from selenium) (1.26.7)
Collecting trio-websocket~=0.9
  Downloading trio_websocket-0.9.2-py3-none-any.whl (16 kB)
Requirement already satisfied: sortedcontainers in c:\programdata\anaconda3\lib\site-packages (from trio~=0.17->selenium) (2.4.0)
Requirement already satisfied: cffi>=1.14 in c:\programdata\anaconda3\lib\site-packages (from trio~=0.17->selenium) (1.14.6)
Requirement already satisfied: attrs>=19.2.0 in c:\programdata\anaconda3\lib\site-packages (from trio~=0.17->selenium) (21.2.0)
Requirement already satisfied: idna in c:\programdata\anaconda3\lib\site-packages (from trio~=0.17->selenium) (3.2)
Requirement already satisfied: sniffio in c:\programdata\anaconda3\lib\site-packages (from trio~=0.17->selenium) (1.2.0)
Requirement already satisfied: async-generator>=1.9 in c:\programdata\anaconda3\lib\site-packages (from trio~=0.17->selenium) (1.10)
Collecting outcome
  Downloading outcome-1.2.0-py2.py3-none-any.whl (9.7 kB)
Collecting exceptiongroup>=1.0.0rc9
  Downloading exceptiongroup-1.1.0-py3-none-any.whl (14 kB)
Requirement already satisfied: pycparser in c:\programdata\anaconda3\lib\site-packages (from cffi>=1.14->trio~=0.17->selenium) (2.20)
Collecting wsproto>=0.14
  Downloading wsproto-1.2.0-py3-none-any.whl (24 kB)
Requirement already satisfied: PySocks!=1.5.7,<2.0,>=1.5.6 in c:\programdata\anaconda3\lib\site-packages (from urllib3[socks]~=1.26->selenium) (1.7.1)
Collecting h11<1,>=0.9.0
  Downloading h11-0.14.0-py3-none-any.whl (58 kB)
Installing collected packages: outcome, h11, exceptiongroup, wsproto, trio, trio-websocket, selenium
Successfully installed exceptiongroup-1.1.0 h11-0.14.0 outcome-1.2.0 selenium-4.8.0 trio-0.22.0 trio-websocket-0.9.2 wsproto-1.2.0

というメッセージが表示されて、あっさりインストールできました。コマンドウインドウとかでやる必要はなかったんですね。

 This version of ChromeDriver only supports

これで動くかと思いきや、今度は、

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 96
Current browser version is 109.0.5414.120

というエラー。これはお馴染みで、ChromeDriverが古いよということです。ウェブブラウザが勝手に自動更新しているのでChromeDriverはそのたびに手作業で新しくしないといけないのが面倒。

https://chromedriver.chromium.org/downloads

から自分のクロームのバージョンに合ったドライバーのバージョンをダウンロードしました。ダウンロードしたchromedriver.exeをスクリプトと同じフォルダに移動させました。

AttributeError: ‘WebDriver’ object has no attribute

これでスクリプトは実行できましたが、今度は、

AttributeError: 'WebDriver' object has no attribute 'find_element_by_id'

というエラー。以前は動いたスクリプトですが、ドライバーのバージョンが変わったらダメになったようです。

AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'

別のスクリプトでも同様のエラーが。なんてこった。以前動いたプログラムが動かなくなるのは非常にストレスです。なぜなら自分の作業の再現性が取れないから。

Seleniumのバージョン変更に伴う仕様の変更に関してはネット上で解説記事がありました。

  1. Selenium4ではfind_element_by_id、nameは非推奨 2022年5月23日 2022年9月19日
  2. Seleniumで「WebDriver object has no attribute」が起きた時の対策と解決法 2023.01.14 2022.08.20
  3. 【Selenium】急にAttributeError: ‘WebDriver’ object has no attributeが起きた 投稿日 2022年07月04日 更新日 2022年07月04日  Qiita
  4. https://stackoverflow.com/questions/72773206/selenium-python-attributeerror-webdriver-object-has-no-attribute-find-el

プログラムをせっかく頑張って書いても、こうやってバージョンアップに伴って動かなくなっていくんですよね。これくらいの変更ならたいしたことないですが、自分が15年以上前に書いたLabVIEWのプログラムなんてもう修正する気が起きません。

さて、修正してみますか。まずこの1行が必要です。

from selenium.webdriver.common.by import By

  1. https://www.selenium.dev/selenium/docs/api/py/webdriver/selenium.webdriver.common.by.html

あとはネット記事を参照します。

書き直す前の文

elem_search = browser.find_element_by_id(‘user-search-text’)

書き直した後の文

elem_search = browser.find_element(By.ID,‘user-search-text’)

まあちょっと修正するだけなので、どうってことなかったです。これで以前と同じようにスクリプトが動作しました。

自分が過去につくった.jpnbファイルを探すプログラム

JupyterNotebookをたくさんつくると、どの作業をするのにつかったプログラムファイルがどれだったかわからなくなってきます。何か手がかりになる検索語があれば、その単語を含むスクリプトを検索するということが、可能です。

自分の場合、そのスクリプトで作業した結果をエクセルファイルなどに出力していることが多いので、その出力ファイル名を手掛かりに、その出力ファイルを作る作業をさせたプログラムを探すことができます。

# JupyterNotebookSearch.jpnb
# 目的:自分が過去につくったスクリプトを、スクリプト内で使った単語で検索

import glob

filenames = ‘*.ipynb’
query = ‘東京’

for filepath in glob.iglob(filenames, recursive=True):
with open(filepath, encoding=’utf-8′) as file:
s = file.read()
if (s.find(query) > -1):
print(filepath)#検索語をスクリプト内に含むファイル名を列挙

PDFの各ページを自動的にスクリーンキャプチャする方法 python programming

保護されたPDFの場合、一定期間が経過すると閲覧できなくなるものがあります。しかしどうしても手元に記録として残しておきたい場合もあるかもしれません。そんな場合の苦肉の策としてPDFをスクリーンキャプチャしておくということが考えられます。しかしそのPDFが何百ページもあると手作業で行うことは現実的でありません。そこでpythonプログラミングで自動的にスクリーンキャプチャするコードを作りました。

# PDFをスクリーンキャプチャー
# アドビアクロバットプロでPDFを開いている前提。それとJupyterを動かしているウェブブラウザ以外は、アプリケーションやウインドウは開かないこと。
# http://python.geo.jp/

import pyautogui
from datetime import datetime
import time

pyautogui.hotkey(‘alt’, ‘esc’)#PDFのウインドウを前に
pyautogui.hotkey(‘alt’,’v’)#アドビアクロバットプロ メニューで「表示」を選択全画面表示
pyautogui.keyDown(‘f’)#アドビアクロバットプロ 全画面表示
time.sleep(5)#needs enough time 最初はこれくらい必要

for i in range(100):#PDFのページの全ページ数の数字を入れること

screen_shot = pyautogui.screenshot() #スクリーンキャプチャー
t = datetime.now()
current_time = t.strftime(“%Y%m%d_%H%M%S_”)#現在時刻をファイル名に使うため

#画像を保存 保存したければコメントアウトすること
# screen_shot.save(current_time+str(t.microsecond)+’.png’)

pyautogui.press(‘enter’)#画面を次のページに
time.sleep(1)#needs enough time 1秒で十分だった。0.5秒でもよかったかも。

 

JSONとは?

JSONというものをときどき、いや、しばしば見かけるのですが、これが何者なのかがよくわかりませんでした。

JSONとは

下の記事が、完全な初心者には優しい解説でした。とりあえず拒絶反応が起きないようにする効果があります。

表形式では表現が困難な構造のデータを、人間に対するある程度の可読性を残しつつ、コンピュータに対しても伝達できるような記法、その1つがJSONです。(非エンジニアに贈る「具体例でさらっと学ぶJSON」 2015年05月28日 classmethod.jp

JSONは多くのプログラミング言語で利用可能である。例えば、ActionScript, C, C++, C#, ColdFusion, Common Lisp, Curl, D言語, Delphi, E, Erlang, Groovy, Haskell, Java, JavaScript (ECMAScript), Lisp, Lua, ML, Objective-C, Objective CAML, Perl, PHP, Python, R, Rebol, Ruby, Scala, Squeakなど。(JavaScript Object Notation ウィキペディア)

 

PythonによるJSONの取り扱い

わかりやすい説明。

JSON ファイルを扱うには、まず JSON ファイルからデータを読み込む必要があります。
JSON ファイルを読み込む手順は
(1)JSON ファイルを開く
(2)開いたファイルを JSON として読み込む
の 2 ステップです。具体的には、以下のように記述します。(qiita.com