#FileNotFoundError
Explore tagged Tumblr posts
aritany · 10 months ago
Text
ultimate betrayal: forgetting the revolutionary idea you just had right as you get your document open
46 notes · View notes
techdirectarchive · 8 months ago
Text
Fix FileNotFoundError: [Errno 2] No such file or directory
In this article, you will learn how to fix FileNotFoundError: [Errno 2] No such file or directory. A FileNotFoundError occurs in Python when you try to access a file that doesn’t exist in the specified directory or path. Please see how to “Enable the Virtual Machine Platform Windows Feature and ensure Virtualization is enabled in the BIOS“, and how to Visualize MBAM Recovery Audit Report with…
0 notes
furbtasticworksofart · 9 months ago
Text
launch: program 'DisassemblyDroneAS:\Users\SerialDesignation████ █ ███ █ █████\Desktop\ConsoleApp\a.exe' does not exist. DroneNameImput: "███████" FileNotFoundError: [Errno 2]
...
DroneNameImput: "CiCi"
Tumblr media
7 notes · View notes
redbrenox · 19 days ago
Text
SCRT
from datetime import datetime
# Melding start van het programma
print("= = = programma kentekensignalering gestart = = =", datetime.now())
# Vraag of vals.txt leeggemaakt moet worden
leegmaken = input("Bestand Vals.txt leegmaken? (j/n): ")
try:
    rdwInput = open("C:\\Users\\ExStudent\Desktop\\P2-K1 (scripting)\\P2-K1-W2 30-05-24\\RDW.csv")
    scanInput = open("C:\\Users\\ExStudent\Desktop\\P2-K1 (scripting)\\P2-K1-W2 30-05-24\\GescandeData.csv")
    if leegmaken.lower() == 'j':
        signaleringen = open("C:\\Users\\ExStudent\Desktop\\P2-K1 (scripting)\\P2-K1-W2 30-05-24\\vals.txt" , "w")
    else:
        signaleringen = open("C:\\Users\\ExStudent\Desktop\\P2-K1 (scripting)\\P2-K1-W2 30-05-24\\vals.txt" , "a")
except FileNotFoundError:
    print("Een van de bestanden kon niet worden gevonden.")
    exit()
aantalVerwerkt = aantalFout = 0
for auto in scanInput:      
    if len(auto) < 10:      
        continue
    autoDelen = auto.split(",")
    scanKenteken = autoDelen[0]
    scanMerk = autoDelen[1]
    scanType = autoDelen[2].replace("\n", "")  
    match = 0                  
    rdwInput.seek(0)            
    for rdwAuto in rdwInput:  
        rdwAutoDelen = rdwAuto.split(",")
        rdwKenteken = rdwAutoDelen[0]
        rdwMerk = rdwAutoDelen[2]
        rdwType = rdwAutoDelen[3].replace("\n", "")  
        if scanKenteken == rdwKenteken:  
            match = 1
            break
    if match == 0:              
        aantalFout += 1
        print("Onbekend kenteken: ", scanKenteken, scanMerk, scanType, "\n\n")
        signaleringen.write("Onbekend," + scanKenteken + "," + scanMerk + "," + scanType + "\n")
    else:                      
        if scanMerk != rdwMerk or scanType != rdwType:  
            aantalFout += 1
            print("Onjuist kenteken:", scanKenteken, scanMerk, scanType)
            print("Geregistreerd op:", rdwKenteken, rdwMerk, rdwType, "\n\n")
            signaleringen.write("Onjuist," + scanKenteken + "," + scanMerk + "," + scanType + "\n")
# Bijgewerkt bestand vals.txt
print("Bijgewerkt bestand vals.txt:")
with open("C:\\Users\\ExStudent\Desktop\\P2-K1 (scripting)\\P2-K1-W2 30-05-24\\vals.txt", "r") as file:
    for line in file:
        print(line.strip())
# Overzicht van de eindtotalen
print("Eindtotalen KentekenCheck:", aantalVerwerkt, "gescande voertuigen,", aantalFout, "fouten gevonden.")
rdwInput.close()
scanInput.close()
signaleringen.close()
# Een afsluitende boodschap
print("= = = programma kentekensignalering afgesloten = = =", datetime.now())
Tumblr media Tumblr media
0 notes
jinxypoodle · 3 months ago
Text
Ip address: 127.0.0.1:8000 Nightspace Chat
import socket from http.server import HTTPServer, BaseHTTPRequestHandler import argparse import threading import webbrowser import urllib.parse
class HTMLHandler(BaseHTTPRequestHandler): """Handles HTTP requests and serves HTML from input."""def do_GET(self): """Handles GET requests.""" if self.path.startswith('/'): if '?' in self.path: query = urllib.parse.urlsplit(self.path).query query_components = urllib.parse.parse_qs(query) if 'myTextbox' in query_components: text_input = query_components['myTextbox'][0] self.server.messages.append(text_input) # Add message to the list print(f"Text box input: {text_input}") self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() message_list_html = "".join([f"<p>{msg}</p>" for msg in reversed(self.server.messages)]) #reversed to show most recent first. html_with_textbox = self.server.html_content + f""" <br><br> <form action="/" method="GET"> <input type="text" id="myTextbox" name="myTextbox" placeholder="Type here..."> <input type="submit" value="Submit"> </form> <br> {message_list_html} """ self.wfile.write(html_with_textbox.encode('utf-8')) else: self.send_response(404) self.end_headers()
def run_server(ip_address, port, html_content): """Starts an HTTP server with dynamic HTML content.""" try: server = HTTPServer((ip_address, port), HTMLHandler) server.html_content = html_content server.messages = [] # Initialize message list print(f"Serving dynamic HTML on http://{ip_address}:{port}") server.serve_forever() except OSError as e: if e.errno == 98: print(f"Error: Address {ip_address}:{port} is already in use.") else: print(f"An unexpected Error occurred: {e}") except KeyboardInterrupt: print("\nStopping server…") server.shutdown() print("Server stopped.")
if name == "main": parser = argparse.ArgumentParser(description="Serve dynamic HTML from input.") parser.add_argument("-p", "--port", type=int, default=8000, help="Port number to listen on.") parser.add_argument("-i", "--ip", type=str, default="127.0.0.1", help="IP address to listen on.") parser.add_argument("-o", "--open", action="store_true", help="Open the webpage in a browser automatically.") parser.add_argument("-f", "--file", type=str, help="Read HTML content from a file.") parser.add_argument("html_content", nargs="*", help="HTML content to serve (as command-line arguments).")args = parser.parse_args() html_content = "" if args.file: try: with open(args.file, 'r') as f: html_content = f.read() except FileNotFoundError: print(f"Error: File '{args.file}' not found.") exit(1) elif args.html_content: html_content = " ".join(args.html_content) else: html_content = input("Enter HTML content: ") server_thread = threading.Thread(target=run_server, args=(args.ip, args.port, html_content)) server_thread.daemon = True server_thread.start() if args.open: webbrowser.open(f"http://{args.ip}:{args.port}") server_thread.join()
0 notes
renatoferreiradasilva · 4 months ago
Text
Tumblr media
try: from kivy.app import App from kivymd.app import MDApp from kivy.uix.boxlayout import BoxLayout from kivymd.uix.button import MDRaisedButton from kivymd.uix.textfield import MDTextField from kivymd.uix.label import MDLabel import requests import qrcode from cryptography.fernet import Fernet from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import rsa, padding import hashlib import jwt import sounddevice as sd import numpy as np import os import json from datetime import datetime, timedelta except ModuleNotFoundError as e: print(f"Erro: {e}. Certifique-se de que todas as dependências estão instaladas.") exit(1)
SERVER_URL = "https://secure-chat.example.com" # Usar HTTPS em produção! TOKEN_FILE = "user_token.secure" KEY_FILE = "fernet_key.secure"
class SecureStorage: @staticmethod def generate_key(): if not os.path.exists(KEY_FILE): key = Fernet.generate_key() with open(KEY_FILE, "wb") as f: f.write(key)@staticmethod def get_fernet(): if not os.path.exists(KEY_FILE): SecureStorage.generate_key() with open(KEY_FILE, "rb") as f: return Fernet(f.read()) @staticmethod def save_token(token): SecureStorage.generate_key() encrypted_token = SecureStorage.get_fernet().encrypt(token.encode()) with open(TOKEN_FILE, "wb") as f: f.write(encrypted_token) @staticmethod def load_token(): try: with open(TOKEN_FILE, "rb") as f: return SecureStorage.get_fernet().decrypt(f.read()).decode() except FileNotFoundError: return None
class LoginScreen(BoxLayout): def init(self, **kwargs): super().init(orientation="vertical", **kwargs) self.username = MDTextField(hint_text="Usuário") self.add_widget(self.username) self.password = MDTextField(hint_text="Senha", password=True) self.add_widget(self.password) self.login_button = MDRaisedButton(text="Login", on_press=self.login) self.add_widget(self.login_button) self.register_button = MDRaisedButton(text="Registrar", on_press=self.register) self.add_widget(self.register_button) self.status_label = MDLabel(text="Bem-vindo! Faça login.") self.add_widget(self.status_label) def login(self, instance): try: hashed_password = hashlib.sha256(self.password.text.encode()).hexdigest() data = {"username": self.username.text, "password": hashed_password} response = requests.post(f"{SERVER_URL}/login", json=data, timeout=5) if response.status_code == 200: token = response.json().get("token") SecureStorage.save_token(token) app.switch_to_chat() else: self.status_label.text = "Credenciais inválidas!" except requests.RequestException: self.status_label.text = "Erro de conexão!" def register(self, instance): try: private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) public_key = private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ).decode() hashed_password = hashlib.sha256(self.password.text.encode()).hexdigest() data = {"username": self.username.text, "password": hashed_password, "public_key": public_key} response = requests.post(f"{SERVER_URL}/register", json=data, timeout=5) self.status_label.text = response.json().get("message", "Erro desconhecido") except requests.RequestException: self.status_label.text = "Erro de conexão!"
class SecureMessengerApp(MDApp): def build(self): self.theme_cls.theme_style = "Dark" self.login_screen = LoginScreen() return self.login_screen
if name == "main": app = SecureMessengerApp() app.run()
Atenção: Não Verificado Ainda
0 notes
learning-code-ficusoft · 5 months ago
Text
Tips for managing exceptions and debugging Python code.
Managing exceptions and debugging effectively in Python is crucial for writing reliable and maintainable code. Here are some key tips to help with exception handling and debugging:
1. Use Try-Except Blocks Wisely
Wrap only the code that might raise an exception in try blocks.
Catch specific exceptions instead of using a general except Exception to avoid masking unexpected issues.
pythontry: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}")
2. Use the Else Clause in Try-Except Blocks
The else clause runs only if no exception occurs, keeping your code cleaner.
pythontry: num = int(input("Enter a number: ")) except ValueError: print("Invalid input! Please enter a number.") else: print(f"Valid number: {num}")
3. Leverage Finally for Cleanup
The finally block runs regardless of whether an exception occurred, useful for resource cleanup.
pythontry: file = open("data.txt", "r") content = file.read() except FileNotFoundError: print("File not found!") finally: file.close() # Ensures the file is closed even if an error occurs
4. Raise Custom Exceptions for Clarity
Define custom exceptions when the built-in ones don’t convey the specific issue.
python class CustomError(Exception): passdef check_value(val): if val < 0: raise CustomError("Negative values are not allowed.")try: check_value(-5) except CustomError as e: print(f"Custom Exception Caught: {e}")
5. Use Logging Instead of Print
The logging module provides better error tracking, filtering, and logging to files.
pythonimport logginglogging.basicConfig(level=logging.ERROR, filename="error.log")try: value = int("abc") except ValueError as e: logging.error(f"ValueError occurred: {e}")
6. Debug with Python Debugger (pdb)
The built-in pdb module allows interactive debugging.
pythonimport pdbdef buggy_function(): x = 10 y = 0 pdb.set_trace() # Execution will pause here for debugging return x / ybuggy_function()
Use commands like n (next line), s (step into), c (continue), q (quit).
7. Use Assertions for Debugging
Use assert to check conditions during development.
pythondef process_data(data): assert isinstance(data, list), "Data must be a list" return sum(data) / len(data)process_data("Not a list") # Raises AssertionError
8. Handle Multiple Exceptions Separately
Avoid catching multiple exception types in a single block if they need different handling.
pythontry: num = int(input("Enter a number: ")) result = 10 / num except ValueError: print("Invalid number!") except ZeroDivisionError: print("Cannot divide by zero!")
9. Use Tracebacks for Better Error Analysis
The traceback module provides detailed error information.
pythonimport tracebacktry: 1 / 0 except Exception: print(traceback.format_exc())
10. Use IDE Debugging Tools
Modern IDEs like PyCharm, VS Code, and Jupyter Notebooks have built-in debuggers that allow breakpoints and step-through debugging.
0 notes
codefrombasics12345 · 8 months ago
Text
Error Handling in Python: Try, Except, and More
Python, like many programming languages, uses error handling to catch and manage exceptions, preventing your programs from crashing. By implementing proper error handling, you can ensure smoother user experiences and more maintainable code. In this blog, we will dive into the basics of handling errors in Python using the try, except, finally, and else blocks.
Tumblr media
Basics of Error Handling in Python
Errors or exceptions in Python come in many forms: ValueError, ZeroDivisionError, FileNotFoundError, etc. The simplest way to handle these errors is by using a try and except block.
try:
    x = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
In this example, the code inside the try block attempts to divide by zero, which would normally cause a crash. However, with except, the program catches the ZeroDivisionError and prints a user-friendly message.
Multiple Exceptions
You can handle multiple exceptions by specifying them in the except block or by using separate blocks.
try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("You must enter a valid number!")
except ZeroDivisionError:
    print("You can't divide by zero!")
Here, if the user enters something that is not a number, the ValueError will be caught. If they enter zero, the ZeroDivisionError will be caught. Multiple except blocks allow for more granular error handling.
Using else and finally
Python allows for even more control using else and finally. The else block executes only if no exceptions are raised, while the finally block always runs, regardless of whether an exception occurs.
try:
    file = open('data.txt', 'r')
    content = file.read()
except FileNotFoundError:
    print("The file does not exist.")
else:
    print("File read successfully!")
finally:
    print("Closing file.")
    file.close()
In this example, the else block runs if no exception occurs during file opening and reading. Regardless of the outcome, the finally block ensures that the file is closed.
Custom Exceptions
You can also define your own exceptions by subclassing Python’s built-in Exception class. This is useful when you need more specific error reporting for custom scenarios.
class NegativeNumberError(Exception):
    pass
def check_positive(number):
    if number < 0:
        raise NegativeNumberError("Negative numbers are not allowed!")
In this case, a custom exception is raised if the number is negative, offering precise control over error conditions.
Conclusion
Error handling is a critical part of Python programming, making your code robust and user-friendly. By mastering try, except, else, and finally, you can prevent unexpected crashes and create a smoother user experience.
Want to learn more about Python? Enroll in our Python for Beginners course now and master error handling, data structures, and more!
0 notes
nugget-soup · 11 months ago
Note
import requests
from requests_oauthlib import OAuth1
import json
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
import pickle
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import pyperclip
# Replace these values with your Tumblr API credentials
CONSUMER_KEY = 'IPTeKkiLSZ2wQ1io5vo5G37AN2thcbSwXOJgqL4SjHV2wLoNce'
CONSUMER_SECRET = 'lE97QdUIAj7svMGDznbcxmsFubj1iIr06hHJ4cLGCaM2wedIio'
TOKEN = 'wovWkA5KSv6XAbMvf5gkAr2V0hGyoRpxbdgM0uoN6qsSzg5OsI'
TOKEN_SECRET = 'gkDd6pBbvsPbUp0Eh95AQQp2CQi5qFzKNtvJ0qPo0far60BqxD'
# CONSUMER_KEY = 'wye8qq5zYT875se51OwUNwPaUvFjvE5ONkzYZ2nsgkoEXnUQfv'
# CONSUMER_SECRET = 'QxLe87coDa0NFzCZRS4KR6gOCxRIEzMqLzOVrH0hc1CVsUjJ35'
# TOKEN = 'fweQkfHHtNWgWiS8KOOFA6bzljfA47cldg44FkljdUbtaV51Uz'
# TOKEN_SECRET = 'l9uS5eLJ2XkRb8D93avCUTeLdxp6m8zDwUTTClgpNZjDGHYMFc'
# CONSUMER_KEY = 'ncRYD9hDIu0uV1tFk2bTxm2F3UDuZ1kM6gsTKO7TAIv9ZQ3rcW'
# CONSUMER_SECRET = '94lTdrh6izgyqP79aSI0HpBSvLAg4PiNRzYEHZTxGWrhWsr4MJ'
# TOKEN = 'vdPho0RVxZANZKVV02HzKKGDVbwMbMNdDckj1dy6GEqIXPvsX3'
# TOKEN_SECRET = '4f7Wfm8oc4mZ94BEH2z9P7fcOHt1tm8AoI3LoAThfKsZ1gWFSz'
# Tumblr API endpoints
BASE_URL = "https://api.tumblr.com/v2"
SENT_ASKS_FILE = "sent_asks.json"
BLOG_NAME = "abedalazeiz"
POST_ID = "756236689516691456"
ASK_MESSAGE = ("I know for sure that you can't help all families from Gaza that want to be evacuated from here but at least you can help those who come across your life. You have no idea how mentally and emotionally tiring this is. Asking for help is not easy. But when thinking that the price is my family's life and getting out of here safely, it just pushes me more and more to do this until i reach my goal, be able to attend my university abroad and achieve my doctoral degree dream after awarding prestigious PhD fellowship. Please donate and share to support us standing at this hard time.\n https://gofund.me/d597b8e2")
# OAuth 1.0a authentication
auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, TOKEN, TOKEN_SECRET)
# = ""
options = webdriver.ChromeOptions()
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--start-maximized")
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)
options.page_load_strategy = 'none' #eager
driver = webdriver.Chrome(options=options)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
        Object.defineProperty(navigator, 'webdriver', {
          get: () => undefined
        })
      """
})
def load_sent_asks():
    try:
        with open(SENT_ASKS_FILE, 'r') as file:
            sent_asks = json.load(file)
            print(f"Loaded sent asks: {sent_asks}")
            return sent_asks
    except FileNotFoundError:
        print("No sent asks file found, starting fresh.")
        return []
def save_sent_asks(sent_asks):
    with open(SENT_ASKS_FILE, 'w') as file:
        json.dump(sent_asks, file)
def get_reblogs(after=None):
    url = f"{BASE_URL}/blog/{BLOG_NAME}/notes?id={POST_ID}&mode=likes&limit=20" #reblogs
    if after:
        url += f"&after={after}"
    print(f"Fetching reblogs from URL: {url}")
    response = requests.get(url, auth=auth)
    response.raise_for_status()
    return response.json()
def send_ask(account_name):
    print(f"Sending ask to {account_name}")
    driver.get(f"https://www.tumblr.com/new/ask/{account_name}")
    driver.implicitly_wait(40)
    actions = ActionChains(driver)
    try:
        #loadingSelector = '#glass-container > div > div > div > div > div > div > div.Y21sU > div > div.oDBam > div > div'
        #WebDriverWait(driver, 30).until(EC.invisibility_of_element_located(driver.find_element(By.CSS_SELECTOR, loadingSelector)))
        #actions.key_down(Keys.ENTER).key_up(Keys.ENTER).perform()
        field = driver.find_element(By.CSS_SELECTOR, '#glass-container > div > div > div > div > div > div > div.Y21sU > div > div.oDBam > div:nth-child(2) > div > div:nth-child(4) > div.block-editor-writing-flow > div > div')
        field.send_keys("\n")
        actions.key_down(Keys.LEFT_CONTROL).send_keys('v').key_up(Keys.LEFT_CONTROL).perform()
        askselector = '#glass-container > div > div > div > div > div > div > div.Y21sU > div > div.Q1jRN > div > div > div > button > span'
        ask = driver.find_element(By.CSS_SELECTOR, askselector)
        ask.click()
        WebDriverWait(driver, 60).until(EC.invisibility_of_element_located(ask))
    except Exception as e:
        print("hmmm")
def main():
    print("Starting script...")
    sent_asks = load_sent_asks()
    previousSave = len(sent_asks)
    after = None
    pyperclip.copy(ASK_MESSAGE)
    try:
        with open('cookies.pkl', 'rb') as file:
            cookies = pickle.load(file)
        driver.get('https://www.tumblr.com')
        for cookie in cookies:
            driver.add_cookie(cookie)
        #driver.refresh()
    except FileNotFoundError:
        driver.get('https://www.tumblr.com/login')
        input("Log in to Tumblr and then press Enter to continue...")
        cookies = driver.get_cookies()
        with open('cookies.pkl', 'wb') as file:
            pickle.dump(cookies, file)
    while True:
        data = get_reblogs(after=after)
        reblogs = data.get('response', {}).get('notes', [])
        if not reblogs:
            break
        for reblog in reblogs:
            account_name = reblog['blog_name']
            if account_name in sent_asks:
                print(f"Already sent ask to {account_name}, skipping.")
                continue
            try:
                url = f"https://api.tumblr.com/v2/blog/{account_name}/info"
                response = requests.get(url, auth=auth)
                if response.status_code == 200:
                    blog_info = response.json().get('response', {}).get('blog', {}).get('ask', False)
                    if blog_info:
                        send_ask(account_name)
                        sent_asks.append(account_name)
                        save_sent_asks(sent_asks)
                    else:
                        print(f"{account_name} doesn't accept asks")
                else:
                    return print("request not available")
            except requests.exceptions.HTTPError as e:
                print(f"Failed to process {account_name}")
        after = data.get('response', {}).get('_links', {}).get('next', {}).get('href')
        if not after:
            break
    # url = f"https://api.tumblr.com/v2/blog/impossiblebool/info"
    # response = requests.get(url, auth=auth)
    # if response.status_code == 200:
    #     blog_info = response.json().get('response', {}).get('blog', {}).get('ask', False)
    #     send_ask("impossiblebool")
    # else:
    #     return print(f"impossiblebool doesn't accept asks>>>>")
    print(f"Script finished, new sent asks number: {len(sent_asks) - previousSave}")
if __name__ == "__main__":
    main()
0 notes
vlyssess · 1 year ago
Text
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-2-a1af17f750a5> in <module> 1 import pandas as pd 2 import numpy as np ----> 3 df=pd.read_csv("iris.csv") 4 df /opt/conda/lib/python3.7/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision) 674 ) 675 --> 676 return _read(filepath_or_buffer, kwds) 677 678 parser_f.__name__ = name /opt/conda/lib/python3.7/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds) 446 447 # Create the parser. --> 448 parser = TextFileReader(fp_or_buf, **kwds) 449 450 if chunksize or iterator: /opt/conda/lib/python3.7/site-packages/pandas/io/parsers.py in __init__(self, f, engine, **kwds) 878 self.options["has_index_names"] = kwds["has_index_names"] 879 --> 880 self._make_engine(self.engine) 881 882 def close(self): /opt/conda/lib/python3.7/site-packages/pandas/io/parsers.py in _make_engine(self, engine) 1112 def _make_engine(self, engine="c"): 1113 if engine == "c": -> 1114 self._engine = CParserWrapper(self.f, **self.options) 1115 else: 1116 if engine == "python": /opt/conda/lib/python3.7/site-packages/pandas/io/parsers.py in __init__(self, src, **kwds) 1889 kwds["usecols"] = self.usecols 1890 -> 1891 self._reader = parsers.TextReader(src, **kwds) 1892 self.unnamed_cols = self._reader.unnamed_cols 1893 pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.__cinit__() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._setup_parser_source() FileNotFoundError: [Errno 2] File iris.csv does not exist: 'iris.csv'
1 note · View note
exhydra · 1 year ago
Text
FileNotFoundError: [Errno 2] No such file or directory: 'home/oracle/abc.txt'
Traceback (most recent call last): File "perfbot.py", line 150, in <module> abc = parseabc() File "perfbot.py", line 126, in parseabc file1 = open("home/oracle/abc.txt", 'w') FileNotFoundError: [Errno 2] No such file or directory: 'home/oracle/abc.txt' Solution: When specifying the path, instead of specifying the relative path, just use absolute path which will solve the error. with…
View On WordPress
0 notes
jinxypoodle · 3 months ago
Text
Here is the python code for an ip address html dirrect message box to a server console message! :
import socket from http.server import HTTPServer, BaseHTTPRequestHandler import argparse import threading import webbrowser import urllib.parse
class HTMLHandler(BaseHTTPRequestHandler): """Handles HTTP requests and serves HTML from input."""def do_GET(self): """Handles GET requests.""" if self.path.startswith('/'): if '?' in self.path: query = urllib.parse.urlsplit(self.path).query query_components = urllib.parse.parse_qs(query) if 'myTextbox' in query_components: text_input = query_components['myTextbox'][0] print(f"Text box input: {text_input}") # Print to console self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() html_with_textbox = self.server.html_content + """ <br><br> <form action="/" method="GET"> <input type="text" id="myTextbox" name="myTextbox" placeholder="Type here..."> <input type="submit" value="Submit"> </form> """ self.wfile.write(html_with_textbox.encode('utf-8')) else: self.send_response(404) self.end_headers()
def run_server(ip_address, port, html_content): """Starts an HTTP server with dynamic HTML content.""" try: server = HTTPServer((ip_address, port), HTMLHandler) server.html_content = html_content print(f"Serving dynamic HTML on http://{ip_address}:{port}") server.serve_forever() except OSError as e: if e.errno == 98: print(f"Error: Address {ip_address}:{port} is already in use.") else: print(f"An unexpected Error occurred: {e}") except KeyboardInterrupt: print("\nStopping server…") server.shutdown() print("Server stopped.")
if name == "main": parser = argparse.ArgumentParser(description="Serve dynamic HTML from input.") parser.add_argument("-p", "--port", type=int, default=8000, help="Port number to listen on.") parser.add_argument("-i", "--ip", type=str, default="127.0.0.1", help="IP address to listen on.") parser.add_argument("-o", "--open", action="store_true", help="Open the webpage in a browser automatically.") parser.add_argument("-f", "--file", type=str, help="Read HTML content from a file.") parser.add_argument("html_content", nargs="*", help="HTML content to serve (as command-line arguments).")args = parser.parse_args() html_content = "" if args.file: try: with open(args.file, 'r') as f: html_content = f.read() except FileNotFoundError: print(f"Error: File '{args.file}' not found.") exit(1) elif args.html_content: html_content = " ".join(args.html_content) else: html_content = input("Enter HTML content: ") server_thread = threading.Thread(target=run_server, args=(args.ip, args.port, html_content)) server_thread.daemon = True server_thread.start() if args.open: webbrowser.open(f"http://{args.ip}:{args.port}") server_thread.join()
0 notes
vespasiane · 2 years ago
Text
Try and except blocks: group, as, .errno
When errors are of a similar nature and there's no need to handle them individually, you can group the exceptions together as one by using parentheses in the except line. For example, if the navigation system is under heavy loads and the file system becomes too busy, it makes sense to catch BlockingIOError and TimeOutError together:
def main(): · · · · try: · · · · · · · · configuration = open('config.txt') · · · · except FileNotFoundError: · · · · · · · · print("Couldn't find the config.txt file!") · · · · except IsADirectoryError: · · · · · · · · print("Found config.txt but it is a directory, couldn't read it") · · · · except (BlockingIOError, TimeoutError): · · · · · · · · print("Filesystem under heavy load, can't complete reading configuration file")
If you need to access the error that’s associated with the exception, you must update the except line to include the as keyword. This technique is handy if an exception is too generic and the error message can be useful:
try: · · · · open("mars.jpg") except FileNotFoundError as err: · · · · print("Got a problem trying to read the file:", err)
Got a problem trying to read the file: [Errno 2] No such file or directory: 'mars.jpg'
If you’re catching a more generic OSError exception, which is the parent exception of both FilenotFoundError and PermissionError, you can tell them apart by the .errno attribute:
try: · · · · open("config.txt") except OSError as err: · · · · if err.errno == 2: · · · · · · · · print("Couldn't find the config.txt file!") · · · · elif err.errno == 13: · · · · · · · · print("Found config.txt but couldn't read it")
0 notes
learning-code-ficusoft · 5 months ago
Text
Understanding Python’s Error Handling and Debugging Techniques
Error handling and debugging are essential skills for writing robust Python code. Python provides various techniques to manage and identify errors that may arise during program execution.
1. Error Types in Python:
Python categorizes errors into two main types:
Syntax Errors: These occur when there is a mistake in the structure of the code. Python’s interpreter catches them before the program runs.
python
print("Hello world" # SyntaxError: unexpected EOF while parsing
Exceptions: These occur during execution when the program encounters a runtime issue. Common exceptions include:
ValueError: Raised when an operation or function receives an argument of the correct type but an inappropriate value.
TypeError: Raised when an operation is performed on an object of inappropriate type.
IndexError: Raised when trying to access an element in a list using an invalid index.
FileNotFoundError: Raised when trying to open a file that doesn’t exist.
Example of a runtime exception:
python
x = 10 y = 0 print(x / y) # ZeroDivisionError: division by zero
2. Using try, except, else, and finally:
Python uses these blocks to handle exceptions:
try block: The code that might raise an exception goes here.
except block: Handles the exception if one occurs.
else block: Executes code if no exception was raised.
finally block: Executes code that should run no matter what (whether an exception was raised or not).
Example:pythonCopyEdittry: number = int(input("Enter a number: ")) result = 10 / number except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Invalid input! Please enter a number.") else: print(f"Result: {result}") finally: print("Execution complete.")
3. Raising Exceptions:
You can raise exceptions explicitly using the raise statement. This is useful for custom error handling or for testing purposes.
Example:pythonCopyEdidef check_age(age): if age < 18: raise ValueError("Age must be 18 or older.") return "Access granted."try: print(check_age(16)) except ValueError as e: print(f"Error: {e}")
4. Custom Exceptions:
You can define your own exception classes by sub classing the built-in Exception class.
Example:pythonclass InvalidAgeError(Exception): passdef check_age(age): if age < 18: raise InvalidAgeError("Age must be 18 or older.") return "Access granted."try: print(check_age(16)) except InvalidAgeError as e: print(f"Error: {e}")
5. Debugging Techniques:
Using pdb (Python Debugger): The Python standard library includes the pdb module, which allows you to set breakpoints and step through code interactively.
Example:
python
import pdb x = 10 y = 0 pdb.set_trace() # Sets a breakpoint print(x / y)
Once the program reaches pdb.set_trace(), the debugger will start, and you can enter commands like n (next), s (step into), c (continue), etc.
Using print Statements: For simple debugging, you can insert print() statements to check the flow of execution and values of variables.
Example:
python
def calculate(a, b): print(f"a: {a}, b: {b}") # Debugging output return a + b
Logging: Instead of using print(), Python’s logging module provides more flexible ways to log messages, including different severity levels (e.g., debug, info, warning, error, critical).
Example:
python
import logging logging.basicConfig(level=logging.DEBUG) logging.debug("This is a debug message") logging.info("This is an info message") logging.error("This is an error message")
6. Handling Multiple Exceptions:
You can handle multiple exceptions in one block or use multiple except clauses.
Example:pythontry: value = int(input("Enter a number: ")) result = 10 / value except (ValueError, ZeroDivisionError) as e: print(f"Error occurred: {e}")
Conclusion:
Understanding Python’s error handling mechanisms and debugging techniques is crucial for writing resilient programs. Using try, except, and other error-handling structures allows you to gracefully manage exceptions, while debugging tools like pdb help identify and resolve issues more efficiently.
WEBSITE: https://www.ficusoft.in/python-training-in-chennai/
0 notes
pinkeaglecrusade · 5 years ago
Photo
Tumblr media
Read on this post to know the best methods to fix ‘File not found’ error in MP4 videos. 
Source: https://www.stellarinfo.com/blog/how-to-fix-file-not-found-in-mp4-videos
0 notes
sciencefordragons · 7 years ago
Text
Today’s successful data processing was brought to you by try/except.
For some hecky reason some galaxies make my code cranky so they don’t produce the sky images I need to make more images for processing out of them, so I just stuck in a try/except to handle the FileNotFoundError that kept popping up when it couldn’t make a w1 filter sky image. It’s still weird that this happened for more than one galaxy on the same filter.
I also put in some lines that will write a file that says why a certain galaxy was bypassed in the loop, mostly for my own use for now. It’s nice to know what the problem was so maybe I can go back and fix it in later iterations of my code.
And!! I’m learning how to use GitHub which is very much designed for CS people but will probably be a useful tool for me. It’s so cool that you can work on something on the side so you can keep track of what you changed and go back to versions where things might be less broken than before!
I made something useful that more people than just me might be able to use! I find that really exciting!
0 notes