r/learningpython • • Feb 10 '19

taking a file name (full path) as an argument?

2 Upvotes

Hi, I'm working on a script that takes in a file and parses it line by line.

Right now I have the file path hard coded.

I tried searching a bit but I don't think I have the language to describe what I'm trying to do properly.

I'd love that if I ran

$python3 textParser.py /root/documents/file

then later I could be like:

fileName = argument
file = open(filename,"r")
magicOccurs()
file.close()

Then the program would be, while still a hack, much more scriptable (ex with bash)

How can I translate this logic into code?

Thanks for the help


r/learningpython • • Feb 08 '19

Calculating an average from a csv file

2 Upvotes

Hi,

I have just started to learn python for data analysis and would like to calculate the average of some data of a csv file.

To be more precise, the csv file includes a list of 1000 exam takers and has 2 variables: age, and if they passed the test (0 or 1). My goal is to create a graph with the age on the x axis and the chance of passing the exam on the y axis. Thus, I need to calculate for each age the success ratio, which I have no clue how to do.

Could someone give me a hint on this?

Many thanks!


r/learningpython • • Feb 04 '19

Splitting Columns Based on Rows with Varying Lengths

2 Upvotes

I have a DataFrame like the following:

Tool_NameMeasurements
Tool_A02_04_06
Tool_B02_04
Tool_C02_04_06_08

I would like to split it into the following:

Tool_NameMeasurement 1Measurement 2Measurement 3Measurement 4
Tool_A020406
Tool_B0204
Tool_C02040608

Using:

df[['Measurement 1','Measurement 2','Measurement 3','Measurement 4']] = df.Measurements_Name.str.split("_", expand=True,)

I get a "ValueError: Columns must be same length as key"

What is the correct way to do this?


r/learningpython • • Jan 09 '19

Telnet to switch from jump start server(linux)

2 Upvotes

Hi,

I just want to ask if anyone here has script or idea what method, library etc should. My target is to SHH first from my workstation to Linux jumpstart server then from jumpstart server I'll access the network devices like switch and routers to execute some show commands.

PYTHON SCRIPT ----SSH---> Jumpstart server(ubuntu) ----Telnet---> Network Devices (Cisco)

import base64, time, sys
import paramiko, getpass, telnetlib
 
#ENTER Password
##pword = getpass.getpass('Password: ')
 
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='xxxxx', username='xxxxx', password='xxxxx')
stdin, stdout, stderr = client.exec_command('pwd')
 
for line in stdout:
    print('Teton: ' + line.strip('\n'))
    client.close()

I'm now able to access the jumpstart server from my PC, the next thing is just to telnet from the jumpstart server?

Thank you


r/learningpython • • Nov 12 '18

Checking " in lines

2 Upvotes

I need help checking for " in lines and if there is anything in between i need it converted to a 1 or a specific text Example.

Line 1: Ronnie Cant Swim Without "Parcher nomad

Line 2: Boomer "Its a robot flying" Catcho

And I need to convert everything inside the " with a 1 or anything in between this is PER LINE.

Expected output

Line 1: Ronnie Cant Swim Without 1

Line 2: Boomer 1 Catcho

The issue is, currently I have a Strip and Split that are checking for Keywords in all the lines. so cant go through all the text file twice.


r/learningpython • • Aug 01 '18

tkinter, after and input = no worky

2 Upvotes

I am very new to Python. I apologize for my ignorance.

I am working on a project that would collect visitor information via a swipe of the visitors drivers license.

I am stuck on building the GUI and then waiting for input simultaneously. Once the card is swiped I want to parse the data and fill the input boxes. At that point all the visitor has to do is click submit.

The code I have below causes the GUI to crash when I am using the license_data with the input function. However when I use the preloaded variable with sample data it works fine.

Any help or direction would be much appreciated.

from tkinter import *
import datetime

def add_text():
       label1 = Label(root, text="Guest Data Submitted.")
       label1.pack()

def clear():
	visitor_name_text_box.delete(0,'end')
	lnumber_text_box.delete(0,'end')
	state_text_box.delete(0,'end')

def data_collector():
	#Test data without using input
	license_data = '%OHCOLUMBUS^BOB$JIM$R$^2725 S READY LINE RD^?;6360231920193567=210319780304?+1043031  D A             1603180BLNBLU                              Y&//_)     ?'
		
	#license_data = input()
		
	fname = ((license_data.split("$"))[1].split("$")[0])
	lname = ((license_data.split("^"))[1].split("$")[0])
	state = (((license_data.split("%"))[1].split("^")[0])[:2])
	lnumber = (((license_data.split("^?;"))[1].split("=")[0])[6:])
	full_name = fname,lname
	now = datetime.datetime.now()
	checkin_date = "%s/%s/%s"%(now.month,now.day,now.year)
	visitor_name_text_box.insert(INSERT,full_name)
	lnumber_text_box.insert(INSERT,lnumber)
	state_text_box.insert(INSERT,state)
		
root = Tk()
root.title("Guest Check-In")
root.geometry("450x200")

visitor_name_label = Label(root, text="Name:")
visitor_name_label.pack()

visitor_name_text_box = Entry(root, bd=1)
visitor_name_text_box.pack()

lnumber_label = Label(root, text="License #:")
lnumber_label.pack()

lnumber_text_box = Entry(root, bd=1)
lnumber_text_box.pack()

state_label = Label(root, text="State:")
state_label.pack()

state_text_box = Entry(root, bd=1)
state_text_box.pack()

enter_button = Button(root, text="Enter", command=add_text)
enter_button.pack()

clear_button = Button(root, text="Clear", command=clear)
clear_button.pack()

root.after(1000,data_collector)
root.mainloop()

r/learningpython • • Jul 22 '18

None of the functions in my program work.

2 Upvotes

I can't find any errors and the IDE doesn't give any suggestions. Simple beginner's glossary program. Here's the code. Thanks.

import os
import pickle
################TITLE######################################
def title():
    os.system('cls')
    print('********************************************')
    print('***************GLOSSARY ********************')
    print('*******************************************\n')
################################VARIABLES##################
py_words = {'iterable': 'an object capable of returning it s members one at a time.',
            'attribute': 'a value associated with an object which is referenced by name.',
            'slice': 'an object returning a portion of a sequence.',
            }
#################################PICKLE&DUMP###############

#Save the contents of the library.
def load():
    # Load the contents of the library.
    try:
        file_object = open('py_words.pydata', 'rb')
        pickle.load(file_object)
        file_object.close()
        return py_words
    except Exception as e:
        print(e)
        return {}

def quit():
    try:
        file_object = open('py_words.pydata', 'wb')
        pickle.dump(py_words, file_object)
        file_object.close()
        print('Goodbye.\n\n')
    except Exception as e:
        print(e)

##########################PICKLE&DUMP//######################

############################FUNCTIONS######################

def menu():
    title()
    print('See all words and meanings.[1]')
    print('Add words and meanings.[2]')
    print('Modify a meaning.[3]\n')
    return input ('Choose an option please. (Or Press 4 to quit): \n')

def see_all():
    for key,value in py_words.items():
        print(key.title()+': '+py_words[key])

def display():
    display_message = ""
    for word in py_words:
        display_message += word + " "
    print(display_message)

def add_word():
    new_word = input("What's the new word?:")
    py_words[new_word] = ''
    new_def = input("What's it's definition?: ")
    py_words[new_word] = new_def

def new_definition():
    display()
    word_choice = input("Which word?: ")
    if word_choice in py_words:
        new_def = input("What's the new definition?: ")
        py_words[word_choice] = new_def
    elif word_choice != 'quit':
        print("That word isn't in the glossary.")
    else:
        print("Goodbye.")

############################FUNCTIONS//####################

#############################MAIN PROGRAM##################
load()
choice = ''

while choice != '4':

    menu()

    title()
    if choice == '1':
        see_all()
    elif choice == '2':
        add_word()
    elif choice == '3':
        new_definition()
    elif choice == '4':
        quit()
###########################MAIN PROGRAM//##################

r/learningpython • • Jun 10 '18

Searching the no of occurrences of two words in a paragraph

2 Upvotes

Suppose I have two words seperated by a white space say 'among these', now I want to count no of occurrences of this exact word ' among these' with whitespace and in same order in a paragraph.... How would I do that in python 3. It is easy to do if it is a single word but for two words with whitespace I don't get it, I don't want to split it into a list of separate words and check for them seperately and then check if they come one after another..... Is there any way to do this?


r/learningpython • • May 04 '18

Something weird happens with my game

2 Upvotes

I'm trying to make a simple Tic-Tac-Toe game with Pygame and I have a big problem. I've made it so that the SPACE key writes the symbol and the arrow keys are used to move around. I use a list ("list_") where I store the values for the squares. To know what value to change, I use a variable called "number" and changing it when the player moves.

The problem is, when I press SPACE it seems to change a random square, instead of the selected one. Something must be wrong with "number", but I can't find what it is. I'll mark where the variable is used or modified in the code. If someone can find the problem, I'll be really thankful.

Also, the arrow keys don't work too well. Sometimes it detects them, sometimes it doesn't, sometimes it moves two squares instead of one... I also need some help with that.

P.S.: I know it's probably really simple, but I'm a beginner to Python, so please understand this. Also, I'm Spanish, so please understand any grammar fails.

import pygame
import time
import os
import sys
from pygame.locals import*

list_=['','','','','','','','','']

WIDTH = 186
HEIGHT = 186

class Cursor(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_image("assets/cursor.png", True, 30, 30)
        self.xpos = 0
        self.ypos = 0
        self.realx = 59*self.xpos + 2
        self.realy = 59*self.ypos + 2
        self.number = 0         #################################################
        
    def update(self, keys):
        if self.xpos < 2:
            if keys[K_RIGHT]:
                self.xpos += 1
                self.number += 1      ##############################################
        if self.xpos > 0:
            if keys[K_LEFT]:
                self.xpos -= 1
                self.number -= 1      ##############################################
        if self.ypos < 2:
            if keys[K_DOWN]:
                self.ypos += 1
                self.number -= 3      ##############################################
        if self.ypos > 0:
            if keys[K_UP]:
                self.ypos -= 1
                self.number += 3      ##############################################
        
        self.realx = 59*self.xpos + 2
        self.realy = 59*self.ypos + 2

        return self.number            ##############################################

class cross(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_image("assets/cross.png", True, 30, 0)

class circle(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = load_image("assets/circle.png", True, 0, 0)

def updateSymbols(keys, cursorPos, turn):           #################################
    if keys[K_SPACE] and list_[cursorPos] == '':     ################################
        list_[cursorPos] = turn                                 #################################
        if turn == 'X':
            return 'O'
        elif turn == 'O':
            return 'X'
        elif turn == '' or turn == None:
            return 'X'
    else:
        return turn
        

def load_image(filename, transparent=False, x=0, y=0):
    try: image = pygame.image.load(filename)
    except pygame.error as message:
        raise SystemExit(message)
    image = image.convert()
    if transparent:
        color = image.get_at((x,y))
        image.set_colorkey(color, RLEACCEL)
    return image

def main():
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    screen.fill([232, 244, 66])
    pygame.display.set_caption("TicTacToe")
    background = load_image("assets/background.png", True, 20,20)
    cursor = Cursor()
    o = circle()
    x = cross()

    cursorPos = 0                             #####################################
    turn = 'X'

    #symbol variables
    xpos = 0
    ypos = 0
    rx = 0
    ry = 0
 
    while True:
        xpos = 0
        ypos = 0
        keys = pygame.key.get_pressed()
        for eventos in pygame.event.get():
            if eventos.type == QUIT:
                sys.exit(0)

        cursorPos = cursor.update(keys)        ################################
        turn = updateSymbols(keys, cursorPos, turn)    ##########################
        print(turn)
        screen.blit(background, (0,0))
        for n in range (0,8):
            if xpos < 2:
                xpos += 1
            else:
                ypos += 1
                xpos = 0

            rx = 59*xpos + 7
            ry = 59*ypos + 7
           # print(list_)
            if list_[n] == 'X':
                screen.blit(x.image, (rx, ry))
            elif list_[n] == 'O':
                screen.blit(o.image, (rx, ry))
            elif list_[n] == None:
                print("Error!")
                quit()
        screen.blit(cursor.image,(cursor.realx, cursor.realy))
        pygame.display.flip()
        
        time.sleep(0.1)
        
    return 0
 
if __name__ == '__main__':
    pygame.init()
    main()

r/learningpython • • Apr 15 '18

Network Engineer's First Script - Good?/Bad?

2 Upvotes

Hello all, I am a Network Engineer doing my best to learn Python as I believe scripting and automation is a valuable tool for the future. Below is a script I wrote to lookup IP addresses on a layer 3 Cisco switch, corresponding hostnames, and NIC manufacture from a list of MAC's provided in a text file. The output was then written to a csv.

I am looking for some guidance and critique here. I put this together using various resources found on-line and modified to what I needed. The below script works but what I could have done better?

This was written for a real world need when I needed to identify physical and virtual machines connected to a switch that we lost management plane access to.

#!/usr/bin/env python

import paramiko
import time
import getpass
import re
import csv
from itertools import izip
import socket
import requests

def disable_paging(remote_conn):
    '''Disable paging on a Cisco router'''

    remote_conn.send("terminal length 0\n")
    time.sleep(1)

    # Clear the buffer on the screen
    output = remote_conn.recv(1000)

    return output

def getHost(ip):
    """
    This method returns the 'True Host' name for a
    given IP address
    """
    try:
        data = socket.gethostbyaddr(ip)
        time.sleep(2)
        host = repr(data[0])
        return (host)
    except Exception:
        # fail gracefully
        return "None"

def getMac(mac):
	macvendor = requests.get('http://api.macvendors.com/' + mac).text
	return macvendor

if __name__ == '__main__':
    #LOGIN PROMPT
    print ''
    print '#########################################################'
    print '### This script will log into a layer 3 Cisco switch, ###'
    print '##### lookup IPs from a list of MAC addresses, and ######' 
    print '##### resolve hostnames via system configured DNS. ######'
    print '###### The script will also lookup the NIC vendor. ######'
    print '##### A csv will be generated in the local directory.####'
    print '#########################################################'
    print ''
    ip = raw_input("Layer 3 Device IP:")
    username = raw_input("Username:")
    password = getpass.getpass()
   

    # LIST FILE OF MAC ADDRESSES
    f = open('list.txt','r')
    

    #CREATE LIST AND CLOSE FILE
    macs = f.readlines()
    macs = [x.strip() for x in macs]
    macs = [x.strip(r'\s|\'') for x in macs]
    f.close()

    # Create instance of SSHClient object
    remote_conn_pre = paramiko.SSHClient()

    # Automatically add untrusted hosts (make sure okay for security policy in your environment)
    remote_conn_pre.set_missing_host_key_policy(
         paramiko.AutoAddPolicy())

    # initiate SSH connection
    remote_conn_pre.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False)
    remote_conn = remote_conn_pre.invoke_shell()
    print "Interactive SSH Connection Established to %s" % ip

    #SHOW CURRENT PROMPT
    output = remote_conn.recv(1000)
    print output

    #CREATE LISTS FOR IPS AND HOSTNAMES
    deviceiplist = list()
    hostnamelist = list()
    macvendorlist = list()
    
    #ARP AND DNS LOOKUP
    for x in macs:
     if re.match(r'([a-f0-9]{4}\.[a-f0-9]{4}\.[a-f0-9]{4})', x):
      remote_conn.send("show ip arp " + x)
      remote_conn.send("\n")
      time.sleep(2)
      output = remote_conn.recv(5000)
      deviceip = re.search(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', output)
      if deviceip:
       deviceip = deviceip.group()
       host = getHost(deviceip)
      else:
        deviceip = 'None'
        host = 'None'
      macvendor = getMac(x)
      deviceiplist.append(deviceip)
      hostnamelist.append(host)
      macvendorlist.append(macvendor)
      
      #SHOW RESULTS/PROGRESS
      print str(x)+" "+str(deviceip)+" "+str(host)+" "+str(macvendor)
      
     #WRITE RESULTS TO CSV
     with open('results.csv', 'wb') as r:
      writer = csv.writer(r)
      writer.writerow(["MAC Address", "Device IP", "Hostname", "Vendor"])
      writer.writerows(izip(macs,deviceiplist,hostnamelist,macvendorlist))
    r.close()

r/learningpython • • Dec 24 '17

Generate PDF confirmation for email

2 Upvotes

I work in tourism. We have guests booking tours with us. I have a fancy PDF that has been drawn up as confirmation template, however, the designer has generalised the greeting with "Hello Adventurer", rather than use the guests name, and has left a "form" box for us to manually type the date of the tour.

Is there a way to say have a alert box prompting us to enter the guest name and date, or even export from excel, that generates this nice pdf confirmation with all text maintaining the same font and looking professional, rather than a manual box we have to enter that looks out of place?


r/learningpython • • Sep 29 '16

Binary to Denary converter

2 Upvotes

I need to make a binary -> denary converter in python 3.4.3. I had no idea how to do this so I searched some up on google to teach my self before I attempted it.

I found this really basic one, binary_input= int(input("Enter a binary number: "), 2)
print(binary_input)

which works, but I have no idea how?? I understand why and how everything works except the , 2) part which seems to make the whole thing work.

Can someone explain what the , 2) part does and how it works so I can use it in my work.


r/learningpython • • Apr 28 '26

Scraped the Warframe wiki mod list into a spreadsheet because why not

Thumbnail
reddit.com
1 Upvotes

r/learningpython • • Mar 20 '26

Hey check out my YouTube tutorials about the 2025 AoC problems. I show my Python solutions and explain my approach. Also have Typescript and Scala solutions in my repo. Let me know your feedback!

Thumbnail
youtube.com
1 Upvotes

r/learningpython • • Mar 18 '26

Fixing Errors

Thumbnail reddit.com
1 Upvotes

r/learningpython • • Jan 23 '26

How do i "rerun" a class for a different choice

1 Upvotes

Since i define a class when its first called, is there a way to "recall" it inside of something that required it?

like

Class Name:
  def __init__(self, name)
    self.name = name
  def greeting(self)
    print(self.name, input())

Bob = Name("bob")

class Speak:
  def __init__(self, name)
    self.name = name
  def somethingidk(self)
     print(self.name.greeting())

Speak(Bob)

Does this make sense? i want to be able to recall the initial thing, while requiring it


r/learningpython • • Jan 15 '26

FREE Python Bootcamp

1 Upvotes

I’m running a live, instructor-led Python bootcamp covering basics + advanced concepts.
No recordings, no upsell pitch—just solid Python taught properly.

Cost: Free for the first 10 participants
Format: Live online
Start: This weekend

If you’re serious about learning Python (or fixing weak fundamentals),
DM me for the curriculum and application details.


r/learningpython • • Dec 24 '25

Coaching Python Sessions 1 on 1

1 Upvotes

Hi everyone, Mario Duval here.

I noticed that a lot of you are interested to learn more about python and I truly consider offering 1 on 1 sessions that could help you practice understand and become better.

If you are interested feel free to let me know it will give me an indication if it’s a good idea.


r/learningpython • • Oct 14 '25

I'M AN IT FIRST YEAR COLLEGE I STUDY PYTHON AND I SUDDENLY LOST, I'M LOST NOW AND I WANT TO CREATE A PROJECT CALLED STUDY TRACKER THAT HAVE GRAPHS AND POMODORO TIMER

1 Upvotes

So at first I was in programming python I'm really exited to learn because I slowly understand or rather progression of learning but then as time progress it's getting harder to me to understand topics that started when i learn modules and defining because there is so many modules like how do you find what needed to your program to work I'm very lost right now I don't even know I can handle programming i really want to learn it i really need tips and what to learn, learning the basics is very easy like loops or logical operators but this time is different I hope someone can help me.


r/learningpython • • Jul 19 '25

Mimo Max

1 Upvotes

Sounds pretty cool. Guided step by step python scripting on what looks like VSC however its $25/m. Has anyone tried it or heard feedback?


r/learningpython • • May 04 '25

Pytest for testing Pillow drawing image application

1 Upvotes

I am looking for idea how test app when I do massive amount drawing using Pillow. Using show method I can during execution browsing pictures, but it is not good idea when I am going to create a lot of images for using on weather station. Can anyone share experience how testing this or how approach subject? I want when I change one element how this affect rest and using testing that is showing and placing in correct place.


r/learningpython • • Feb 21 '25

I'm Trying To Install Pytorch But Pip Will Not Install no matter what i do

1 Upvotes

Please ELI5 because I'm very new and very very frustrated

Python is installed correctly, I'm sure I've added the correct PATH but every -pip or -py command brings up a Not Recognized error.

Trying to install it via Python -m pip install -U pip gets me a "no module named pip"

I've been up all night Googling and reading through threads trying to understand what I'm doing wrong but nothing seems to work


r/learningpython • • Feb 01 '25

Learning python for DSA: Any tips for transitioning from basic to advanced

1 Upvotes

Hey everyone! I’ve been learning Python for a while now and have gotten comfortable with the basics. I’m looking to transition into more advanced topics, especially in Data Structures and Algorithms (DSA). Does anyone have advice on how to make that leap? Any resources or strategies that helped you along the way would be much appreciated! Thanks in advance!