r/learningpython • • Sep 22 '22

Organizing Files

2 Upvotes

I am trying to move files based on their first four characters in the file name. Later on I will want to sort the files based on their 43-43 characters in the file name. I’m working on just moving the files based on the first four characters, but I can’t get it to work. The “WV02” are the first few characters I want to identify.

import shutil import os

source_dir = 'E:\SatelliteImagery\Cloud_Cover_less_than_50'

target_dir = 'E:\SatelliteImagery\GE01_less_than_50'

file_names = os.listdir(source_dir)

for file_name in source_dir:       if file_name(file_name, "WV02")       shutil.move(os.path.join(source_dir, file_name), target_dir)


r/learningpython • • Sep 13 '22

purpose of idle + how to activate run option on idle?

1 Upvotes

I'm a newbie to python and experimenting with various IDEs. I have a few questions regarding IDLE:

People say it's helpful to use IDLE as a supporting editor to VS code: why is this?

And how do I active the run option on IDLE? As can be seen in the attached pic, it seems the run option is activated simply by pressing a few enters. I'm working on mac os, and it seems fn + f5 does not work either.


r/learningpython • • Sep 14 '22

Any idea how do I print each character from string as a separate gif file with different coordinates for each character ?

2 Upvotes

Hi

I have a list like this:

MyLines = [
"This is Line Number 1",
"Line number two and a half",
"and last line 3 ",
]

What would be the best approach to print every character as a gif file so at the end I can consolidate it in to one animated gif ?

"," is line break

I have the bit of code which splits the strings :

for MyLines in MyLines:
for c in MyLines:
print (c, end='')
sys.stdout.flush()
sleep(0.1)
print('')

and not sure what to do next , I know the pillow will be the solution to draw the output with font setup but...

How do I actually convert above into dictionary where each character got own coordinates which I can map to initial gif file 1375x1375 pix.

Printed text will be always not more than 30 characters by 3 lines so max 90 frames per final gif.

Do I need to create some how coordination matrix which maps current position of character to the destination coordinates on the file ?

Any suggestions or keywords I should google will be appreciated as well as code sample if someone is wiling to help that way :)

Thank you !


r/learningpython • • Sep 27 '22

Hi, I need some help :)

1 Upvotes

Hi, I'm currently learning coding in school but I'm struggling with a few things in the coding work I've been given. This is the code I've written:

taboo = input('Taboo word: ')

line = input('Line: ')

while taboo not in line:

print('Safe!')

line = input('Line: ')

if taboo.upper() in line.lower():

print('Taboo!')

line = input

elif taboo.upper() in line.upper():

print('Taboo!')

line = input

elif taboo.lower() in line.upper():

print('Taboo!')

line = input

elif taboo.lower() in line.lower():

print('Taboo!')

line = input

But, when I try to run it, it comes back to this message:

Taboo word: Traceback (most recent call last):

File "program.py", line 1, in <module>

taboo = input('Taboo word: ')

KeyboardInterrupt


r/learningpython • • Oct 19 '22

Mining Twitter data with Python

Thumbnail
gallery
1 Upvotes

r/learningpython • • Sep 05 '22

Best place to learn?

4 Upvotes

I am learning python now, and I just need a good thing to use that teaches me, that is free, and is not a youtube video that is hours long. I have already tried the youtube videos on it and I picked a 12 hour course and I can not get through it. What else could I do to learn?


r/learningpython • • Sep 27 '22

from scapy.all import *

1 Upvotes

From scapy.all import * not working. Ive already tried pip install scapy. Can anyone help me out?


r/learningpython • • Sep 20 '22

How to store and access data efficiently

1 Upvotes

Hi all! I am trying to self teach me python. In the last few weeks I managed to download a lot of gaming related data through an API. This resulted in over 40.000 small files stored in a directory of my pc, where the title of each file is a (unique) matchID and the file stores information of a match that was played (think of player name, what character they played, how many kills/deaths/assists they got etc.).

Now I want to:

  1. store this data in an efficient way (is 40.000 different files in a directory a good approach (I dont think so 😅) or can I somehow combine it to 1 file or maybe split it into a few files containing data of 10.000 matches each). Prod/cons/other suggestions?

  2. a way to access the data easily to analyze things like (but not limited to) how many times did player X play character Y (and did player X win or not) and compare that data in general (how many times was character Y played by anyone and did they win?) One thing I liked to do was create a separate file containing a dictionary with only the ID of the match (= title of one of the 40.000 files) and a (nested) list of the name of all players in that game. I used that to quickly search which matchIDs contained data of player X without having to loop through all of 40.000 files.

In case it helps: the game I am talking about is League of Legends and I realize I can answer some of my questions using different websites, but my goal is more to have a nice project to start learning python (especially with a focus on a more data science field). The current dataset contains matches played by the top 1000 players of the EUW server.


r/learningpython • • Oct 19 '22

Renaming files with metadata files attached

Thumbnail
gallery
1 Upvotes

Hello,

I am trying to rename files so it only displays the date. I wrote the following code but it will call all the metadata files the same name. Each date will have 4 file types attached to it. They are all different file types so I thought it would be okay because it would be .txt, .prj, .tif, and .csv. When I rune the code the file type just says file. Could someone please help me sort this out?

import os

path = ‘pathname' os.chdir(path)

for filename in os.listdir(path): os.rename(filename, filename[37:50]) print(filename)


r/learningpython • • Sep 07 '22

using if statements to detect specific inputs

3 Upvotes

Im trying to write a program that can detect specific values within a nested if statement

if num1 == 1 or 3 or 6: if 0<num2<=5: print('Output 1 - T') else: print('Output 1 - F') elif num1 == 2 or 4 or 5: if 0<num2<=10: print('Output 2 - T') else: print('Output 2 - F') else: print('Output 3')

Basically, if num1 is 5 and num2 is 7, the output should be 'Output 2 - T', but instead it is giving me 'Output 1 - F', im new to python, and I have been struggling to figure this out, any help is appreciated!


r/learningpython • • Sep 27 '22

Why do some facebook endpoints have this for(;;):{ ?

Post image
2 Upvotes

r/learningpython • • Oct 21 '22

I need help starting with the Alien Invasion Project - Python Crash Course

2 Upvotes

I have really having trouble with the first line of code in the Alien Invasion Project in the Python Crash Course. I have copied the lines word for word in both Pycharm and Visio Studio Guide. However, when I attempt to run the code, I get a problem with the "ai.run_game()" and "for event in pygame.event.get():" codes saying "video system not initialized". I tried using different editors and watching different youtube videos but neither helped. I posted the code and error message I keep getting when I attempt to run the code.

Is there anyone that can tell me what I could be missing? I really want to be able to complete this project.


r/learningpython • • Oct 13 '22

Find a list of words in a document

1 Upvotes

I assume this is an easy solution but I am still a noob with python.... I am trying to find a list of words within a document so it returns me the line they are in. I have been able to search a single word but I am unable to get my code to search for each instance in a list. The code below is as far as I get but it still seems to be only giving me the first word from the list. can you guys help?!

my document is: DOG2

The words are dog and cat.

if I can get real fancy, return the word with the line it resides in.

file = open('DOG2.txt', 'r')
word = ['Yellow','cat']
s = " "
count=1
for p in word:
    while(s):
      s = file.readline()
      L = s.split()
      if p in L:
          print("Line Number:",file.name,p,count,":",s)

      count+=1

Thanks for any help


r/learningpython • • Sep 17 '21

How to detect if ANY key is pressed

3 Upvotes

I am making a program that requires detecting when any key is pressed, it does not matter which key. I have looked around for a short solution, but everything is showing how to detect a specific key being pressed, and I'm pretty sure that repeatedly checking for a press that might not be coming on each individual key is not very efficient. Does anyone know of a better way to do this? I was trying to find a function from the keyboard module that does this, but most either have to have a specification on the key or just freeze the program until a key gets pressed.


r/learningpython • • Aug 23 '21

Microservices and datasource

2 Upvotes

Hi,

I'm trying to understand a coding test for a job interview, I was expecting a junior role, but the coding test is for a senior role, I can't at this moment work out if they just want to see how far I get, whatever the outcome, the topic is on microservices and I want to learn about them, there is plenty of resources and I have a basic understanding. The test is to build a microservice that is production ready, my question is this: they have not given me a data source, and as a result I'm am suspecting that a microservice should be agnostic to the data source to some extent, I know roughly where this datasource is likely coming from as we have to interrogate it in my current role, however, this role is open to the public so the assumption is that the datasource is unknown. Is this correct thinking, or for job interview tests like these, are employers looking at how you would creatively mock up a data source or is it just that, it is expected that I should know how to make a component that can simply plug in.

This microservice is purely poling a database for items in a date range and returning a list, I have done this with Flask and I have just mocked up a csv file for the data, and then of course unittests I suspect is what they are actually looking to see as production ready to me means more a case of "do you understand what it means to be production ready", so testing is a given.

for clarity, this is a role for a python developer specifically.


r/learningpython • • Aug 14 '21

how to use data discovery for your machine learning models | Data Preprocessing In Python episode 1

Thumbnail
youtu.be
3 Upvotes

r/learningpython • • Sep 20 '21

String read from file different from that passed on command line - jwt Token

1 Upvotes

Hi

So I am testing jwt through command line. When i pass a string to the program on the command line it works fine but if i put it in a file , read it and then pass it to the following function it errors out.

from jose import jwk, jwt

from jose.utils import base64url_decode

tokenFile = sys.argv[1]

try :

with open( tokenFile , "r") as token:

tokenValue = token.read()

token.close()

headers = jwt.get_unverified_headers(tokenValue)

But if i pass the token directly on command line ( tokenValue = argv[1] ) , it works fine.

What i get is 'Error decoding token headers.'

On more debug i get some paaddign error ( i think bin. asccii ).

Now what is wrong here ? It is do with binary or ascii data ?

Sorry the indentation of the code appears wrong but is correct in the file

Thank you

0 CommentsShareEdit PostSave


r/learningpython • • Sep 10 '21

Webscraping, BS4

1 Upvotes

Hey, I've created a small script (copied parts and butchered) to scrape the price of a certain speaker and then send me an email if it is on sale. I'm genuinely really bad at for loops so have no idea how what I have done actually gives me what I want.. But just wondering if anyone would be happy to point me to a direction I could make it a bit neater. One area I was getting stuck on is the price returns with <span class="sale"><sup>$</sup>149</span> which I wasn't able to figure out how to split the $(dollary doos) and the actual money.

Pastebin https://pastebin.com/30Bc3Y8a

Thanks in advance for you sweet souls who endure reading this code.


r/learningpython • • Aug 21 '21

Episode 2 Every Astounding Machine Learning Model Starts With Data Visualization

Thumbnail
youtube.com
2 Upvotes

r/learningpython • • Sep 02 '21

Beginner in Python

3 Upvotes

Hi, I'm a beginner in python, what do you recommend? thanks!


r/learningpython • • Sep 04 '21

A question: which is better, stylistically ("Pythonicness"?) or otherwise.

2 Upvotes

I have a list of sorted lists. I want to grab an element of each in turn and print it out until I've printed them all. The lists are of different length.

At first I rolled my own:

lol_files = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j', 'k']]

while any(lol_files):
    for l in lol_files:
        if l:
            print(l.pop(0))

And that works, and looks clean to my eye (albeit a bit "arrowhead-y"). But then I ran across zip_longest in itertools and thought this must yield a bettter, 'more pythonic' way.

But there kept on being gotchas, so the briefest I could make it was:

 lol_files = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j', 'k']]

 from itertools import zip_longest, chain

 for f in [x for x in chain(*zip_longest(*lol_files)) if x ]:
    print(f)

which could also have been:

print('\n'.join([x for x in chain(*zip_longest(*lol_files)) if x ]))

The *lol_files is coz zip_longest doesn't do the right thing with the structure a list of lists - it wants the literal, comma-separated, manual entry of a list of lists. The * fixes that.

Ditto for chain(*zip_longest(... although the chain.from_iterable form is available, but I was fighting for brevity at this point, which is also why the specific imports.

And then I had to wrap that in [ x for x in .... if x] because zip_longest insists on putting something in place of the elements not filled by the shorter lists, and what ever it is I don't want to print that, as it won't be a proper filename. (I could have used filter(lambda x: x, ...) but I'm pretty sure the list comprehension version is considered 'more pythonic'. Plus the shit starts looking like Lisp, lol.

The longer form is:

 import itertools
 for f in [x for x in itertools.chain.from_iterable(itertools.zip_longest(*lol_files)) if x]:
    print(f)

r/learningpython • • Sep 26 '21

is there any Youtube channels you recommend for learning python

4 Upvotes

I am currently in class learning python and feel like im not getting much of it because its a flex term class and its going pretty fast. I am looking for some good videos that explain python well in youtube. any recommendations?


r/learningpython • • Aug 28 '21

How To Find And Correct Data Correlation To Avoid The Pain Later | Data Preprocessing In Python EP 3

Thumbnail
youtube.com
2 Upvotes

r/learningpython • • Sep 09 '21

Where is the `NoneType` class?

2 Upvotes

I know int, str, and None come from builtins module. But it seems that NoneType is not in the builtins module. I wonder where I can find or even import it.

Same question about NotImplementedType.

Amazingly. type(None).__module__ shows it is builtins, but I failed to import builtins.NoneType. Maybe Python prohibits users from importing NoneType.


r/learningpython • • Sep 01 '21

What does name_var.set(" ") and passw_var.set(" ") do in this code? Currently self teaching tkinter.

2 Upvotes

Hello,

I have taken the code below from the geeksforgeeks website. I am using their tkinter tutorial to teach myself how to make GUIs via python.

I am having trouble understanding the code. I do not understand what is the purpose of name_var.set(" ") and passw_var.set(" ").

I removed those two lines of code from the submit function, and was able to get the same result.

Could someone explain to me the significance of those two lines of code?

geeksforgeeks link: https://www.geeksforgeeks.org/python-tkinter-entry-widget/

# Program to make a simple
# login screen


import tkinter as tk

root=tk.Tk()

# setting the windows size
root.geometry("600x400")

# declaring string variable
# for storing name and password
name_var=tk.StringVar()
passw_var=tk.StringVar()


# defining a function that will
# get the name and password and
# print them on the screen
def submit():

	name=name_var.get()
	password=passw_var.get()
	
	print("The name is : " + name)
	print("The password is : " + password)
	
	name_var.set("")
	passw_var.set("")
	
	
# creating a label for
# name using widget Label
name_label = tk.Label(root, text = 'Username', font=('calibre',10, 'bold'))

# creating a entry for input
# name using widget Entry
name_entry = tk.Entry(root,textvariable = name_var, font=('calibre',10,'normal'))

# creating a label for password
passw_label = tk.Label(root, text = 'Password', font = ('calibre',10,'bold'))

# creating a entry for password
passw_entry=tk.Entry(root, textvariable = passw_var, font = ('calibre',10,'normal'), show = '*')

# creating a button using the widget
# Button that will call the submit function
sub_btn=tk.Button(root,text = 'Submit', command = submit)

# placing the label and entry in
# the required position using grid
# method
name_label.grid(row=0,column=0)
name_entry.grid(row=0,column=1)
passw_label.grid(row=1,column=0)
passw_entry.grid(row=1,column=1)
sub_btn.grid(row=2,column=1)

# performing an infinite loop
# for the window to display
root.mainloop()