This question already has answers here:
Open document with default OS application in Python, both in Windows and Mac OS
(17 answers)
Closed 4 years ago.
So I wanted to create code that creates fake steam keys/adobe keys to fool my friends into thinking I can get as many games as I want. So I got everything working as planned, the code generates the steam key and then places it into a .txt file.
However I find it very annoying that I need to keep manually reopening the file after every time I type "y" in the if another == "y": line to access the new key. I was wondering if it is possible to have it open the .txt file for me. I have looked through many websites and can't find anything that actually launches the .txt. Hope someone can help me out here, full code is as follows:
import string
import subprocess
import sys
import random
from random import *
while True:
def steam():
while True:
min_char = 5
max_char = 5
allchar = string.ascii_letters + string.digits
password1 = str("".join(choice(allchar) for x in range(randint(min_char, max_char))))
password2 = str("".join(choice(allchar) for x in range(randint(min_char, max_char))))
password3 = str("".join(choice(allchar) for x in range(randint(min_char, max_char))))
f = open('Steam Keygen.txt','w')
f.write(password1.upper() + "-" + password2.upper() + "-" + password3.upper())
f.close()
steampath = r'C:\Users\mynamewhichIdontwanttoshare\Desktop\Steam Keygen.txt'
subprocess.Popen(",s ,s" , (steampath))
another = input("Another?")
if another == "y":
print("Ok!")
steam()
else:
sys.exit(0)
def first():
watchuwant = input("What software do you want a code for?")
if watchuwant == "steam":
steam()
elif watchuwant == "adobe":
adobe()
else:
print("This is not available, sorry.")
first()
Note:
The adobe() function doesn't work yet so if you want to run it, just test by typing:
-What software do you want a code for?
steam
-Another?
y
If you're trying to get the same result as you would by double-clicking the file, you're looking for os.startfile(). With this, you need to specify a filepath, and when called, this function will 'launch' the file (in this case, your .txt file). The file is opened with whatever application (if any) its extension is associated with.
Usage:
import os
os.startfile('textfile.txt')
This will 'launch' the text file.
Also, as #heather says in the comments, if you only use the filename (and not the filepath), your program will only work if the steam key text file is in the same directory - otherwise, you have to put in the full filepath.
Related
I am using Python to create a list of groups. It only makes sense to me that, using the code, I have for creating the password protected zip, I can create the input in my code as long as it is created before listing the input. As such, I have created a txt file which then needs to be placed in a password protected zip. With the code I am using below, I get this error message when I try to run it: (OSError: error in opening /Users/name/Desktop/Groups.txt for reading). I'm simply not very experienced in this regard and wouldn't know how to solve this issue (+ I am extremely desperate right now). This is the code I have so far, but it does not work:
#creates .txt file to put in zip folder
with open("Groups.txt", 'w') as file:
file.write("Each row is a group:" + '\n')
for row in final_group:
s = ", ".join(map(str, row))
file.write(s+'\n')
# creates password protected zip
inpt = "/Users/name/Desktop/Groups.txt"
pre = None
oupt = "/Users/name/Desktop/Groups.zip"
password = "password"
com_lvl = 5
pyminizip.compress(inpt, None, oupt, password, com_lvl)
Could someone help me out here?
The input file might be in a different directory, because of which there's an error. You can either
Set inpt = "Groups.txt"
Set with open("/Users/name/Desktop/Groups.txt", 'w') as file:
So I'm working on a discord bot that has commands like meme commands, roast commands, etc, and since I'm still learning python I haven't started to work with databases yet and store all the roasts in a separate py file and then import it as a module in the bot file.
I want to create another .py file that imports the list and appends to it instead of me opening the py file and edit it myself... heres the code i've written for now and even though it executes without any errors, the list module does not append.
from roasts_list import roast
adder_value = input("What would you like to add? \n")
roast.append(adder_value)
the module is the roasts_list and the list name is roast.
Any solutions?
Rather than creating an external python module for storing the list, you can store it in a text file.
adder_value = input("What would you like to add? \n")
#add roasts to the text file
roast_file = open("roast.txt", "a")
roast_file.write(adder_value + "\n") #adds roast to the text file
roast_file.close()
#get roasts
roast_file = open("roast.txt", "r")
roast_list = roast_file.read().splitlines() #returns a list of all roasts in the text file
roast_file.close()
Using this method, you can save your roasts in text files, and use them accordingly.
Agreeing with Devansh. If you go with your approach to save them in e.g. a list variable from a .py file, that would mean that all of your values would only be stored in memory and as soon as the program stops, all values will be lost. If you want to persistently store the values, the easiest way would be to store them in a file.
In addition to Devansh approach above, i would suggest opening the file with its context manager, and adding a try/except to handle if you try getting roasts from the file before it's created, making it a little bit more stable in a running program.
#add roasts to the text file
def add_roast():
adder_value = input("What would you like to add? ")
with open("roast.txt", "a") as roast_file:
roast_file.write(adder_value + "\n") #adds roast to the text file
#get roasts
def get_roasts():
try:
with open("roast.txt", "r") as roast_file:
return roast_file.read().splitlines()
except FileNotFoundError as e:
print("No roasts exist yet")
add_roast()
print(get_roasts())
I have trying to save images into a directory based on user input. For example:
if user enters 'A'
save in A folder
elif user enters 'B'
save in B folder
and so on.
When I try this two things happen one the folder doesn't fill up and two my loop goes to pieces. I have been trying for a little while with getch() and input() but both are simply not working for me.
here is my code.
getInput = input("Enter Which Window to Save")
if getInput == int('1'):
cardFound = input("Which Card was Found: ")
cardsFound.append(cardFound)
print("\tFlop Cards Found")
print(cardsfound)
print (52 - counter1,"Left to find...")
cv2.imwrite("C:/FlopOne/" + cardFound + ".jpg")
cv2.waitKey(0)
There are lots of elif statements after this all responding to getInput but when the loop gets paused for getInput. my windows (there are five of them) dont turn up there just grey screen. however, if I call waitKey() in order to see my windows then the loop haults and I am stuck unable to gain input. I don't want to have to parse this folder manually.
Note I am only now learning Python.
When dealing with paths and directories, you should use the os.path module. (It's not required, but it makes dealing with paths much easier). This module makes it a little easier to make cross-platorm code that will run on both windows and linux even though the directories and path conventions look different. Below is a little example of choosing directories and writing to them.
This example has a while loop that continually asks for input as long as the input is not 'e'. The user can write to either directory a or directory b. From here we are appending the directory and random filename using os.path.join(). Notice that I am not using unix-style paths or windows-style paths. If you want to run this locally, just be sure to create directory "a" and directory "b".
import os
from random import randint
if __name__ == '__main__':
# This is the current working directory...
base_path = os.getcwd()
while True:
# whitelist of directories...
dirs = ["a", "b"]
# Asking the user for the directory...
raw_input = input("Enter directory (a, b): ")
# Checking to be sure that the directory they entered is valid...
if raw_input in dirs:
# Generating a random filename that we will create and write to...
file_name = "{0}.txt".format(randint(0, 1000000))
# Here we are joining the base_path with the user-entered
# directory and the randomly generated filename...
new_file_path = os.path.join(base_path, raw_input, file_name)
print("Writing to: {0}".format(new_file_path))
# Writing to that randomly generated file_name/path...
with open(new_file_path, 'w+') as out_file:
out_file.write("Cool!")
elif raw_input == 'e':
break
I'm trying to create a program that duplicates itself to another location and creates a batch file on the desktop. I can make it duplicate itself and I can create the batch file but I need some help with the paths.
I can find the path that my program is currently in. Both the direct path and the path to the directory. My problem lies in the fact that I want to place the file in (let's just say for simplicity) 'C:\Users\Me\Documents'. How would I edit the path? I want to be able to place this on a generic windows computer so I can't hard code the path in because each user will be different. This goes the same for placing the batch file and setting it for the right directory to run the python script in documents.
I have tried both
import os
print os.path.dirname(os.path.abspath(__file__))
and
import os
print os.path.abspath(__file__)
but am clueless as to how to edit the path. When I try googling for it and searching this wonderful site, all I get is stuff about configuring the Python path on windows and other stuff that I can't quite understand at my current level of Python.
Now I turn to you, can you help? Any input would be appreciated, if you could explain how it worked that would be even better!
<>
Due to some questions about my code (and a specific one to post it) Here it is
from sys import argv # Imports module
import os
script, create = argv # Gets script name and desired amount of copies
data = open(script) # Creates a variable to store the script
indata = copy.read() # Creates the data to be copied from the script
batData = """
echo off
%s
""" % # This is not finished, creating that batch file
createT = int(create) + 1
for i in range(1, createT): # Runs a set amount of times
copyName = "%s.py" % str(i) # Creates the name for the file
copy = open(copyName, 'w+') # Opens/creates the file for editing
copy.write(indata) # Writies the indata to the file opened
copy.close # Closes that file
batName = "%s.bat" % str(i)
bat = open(batName, 'w+')
It is not finished but hopefully you get the gist. The argv at the beginning is so I can change the amount of copies made, that will be deleted later as I evolve the code but for now I like it there.
I have currently tried the following to find the path:
import os
print os.path.abspath(__file__)
print os.path.dirname(os.path.abspath(__file__))
print os.path.dirname(__file__)
test = os.path.dirname(__file__)
a, b, c, d, e, f, g, h, i = test.split("\\")
print c
What I want to happen (or think I want to happen) is for the path to be found, then split into pieces (either each directory or break off everything after the username). Then I want to append the document folder tag to the end. For the batch instead of the document tag it will be for the desktop.
among a few others that people have posted. I hope this helps!
Your code snippet returns a string. Just take that string and edit to make the path you want. I'm on a mac so I can't test with an actual windows directory but I'll try to make it look Windows-ish. For instance, lets say this code:
directory_path = os.path.dirname(os.path.abspath(__file__))
print(directory_path)
gives you:
C:\Users\username\AppData
You can use the split function to break the path into pieces (docs).
stuff = path_string.split('\')
print(stuff)
Code output:
['C:', 'Users', 'username', 'AppData']
You can use the pieces create the path you want and then use it to write the file. So, if you want the username folder just loop until you find it. Some example code is below (just an example to get you started - read up on Python if you need help understanding the code).
username = ""
for i in range(0, len(stuff)):
if stuff[i] == "Users":
username = stuff[i + 1]
Not sure if that answers your question but hope it helps.
Am I correct that you are trying to figure out how to make a file path to some location on the user's directory without knowing who the user is going to be that is executing the program?
You may be able to take advantage of environment variables for this. For instance, I can get a file path to the C://Users/username/ directory of whoever is executing the code with:
my_path = os.path.join("C:\\", "Users", os.getenv("USERNAME"))
Where os.getenv("USERNAME") returns the value of the USERNAME environment variable (should be the name of the user that is currently logged on).
You can list all of the available environment variables and their values in Python with:
for key, val in os.environ.items():
print("{} \t {}\n".format(key, val)) # or however you want to prettify it
You may get lucky and find an environment variable that gives you most of the path to begin with.
In general, os.path.join(), os.path.relpath(), and os.path.abspath() combined with some environment variables might be able to help you. Check out the os documentation and os.path documentation.
Many times when modifying a path, I am looking to add/remove folders. Here is my simple method for adding a path, e.g. if I want to move the path of an object into a folder added_path='/train/.
Since my paths are usually uniform, I check the last split characters in the first file location. Usually, my experience is that windows have \\ at the end while Mac and Linux have `/', which makes this work across operating systems. (note: if the paths are not uniform, you obviously place the if-else in the for-loop.)
if '\\' in data[0].img_file:
split_char = '\\'
else:
split_char = '/'
for img in data:
img_path = img.img_file.split(split_char)
label_path = img.label_file.split(split_char)
img.img_file = '/'.join(img_path[:-1]) + added_path + img_path[-1]
img.label_file = '/'.join(label_path[:-1]) + added_path + label_path[-1]
So, this for loop uses all the folders up until the file name, where we insert the extra folder, and then, at last, add the file name.
Example input path: 'data/combined/18.png'
Example output path: 'data/combined/train/18.png'
I'm currently playing a trading card game called Hearthstone which is made by blizzard. The game is pretty good, but lacks basic features that any game that calls itself "competitive" should have, like stat tracking and replay.
So as I said in the title, I'm trying to create a (very crude and poorly done) script that let's me record every match I play. Due to my lack of programming skills, 80% of the script is just a bunch of code that I borrowed from all sorts of places and adapted to make it do what I wanted.
The idea is to make it work like this:
I take a picture of every turn I play. It might become annoying, but I do not dare to think about implementing OCR as to make the script take a picture at the start of every turn by itself. Would be awesome but I just can't do it...
The game sends every picture to the desktop (no need to code that).
At the end of the game I run the script
2.1 Every match is going to have a numbered folder so the script creates that. The folders are going to be called "Match1", "Match2", etc. You can see how poorly written that is because I made it on my own :P
import sys
import os
import shutil
def checkFolder():
os.path.join('D:\Hearthstone\Replays\Match1')
matchNumber=1
while os.path.exists("D:\\Hearthstone\\Replays\\Match"+ str(matchNumber)) is True:
matchNumber=matchNumber + 1
else:
os.makedirs("D:\Hearthstone\Replays\Match"+str(matchNumber))
2.2 Script sends the photos from Desktop to the recently created folder. The Problem is that I do not know how to make the script change the destination folder to the newest folder created. I did not write this part of the code, i merely adapted it. Source: http://tinyurl.com/srcbh
folder = os.path.join('C:\\Users\\Felipe\\', 'Desktop') # Folder in which the images are in.
destination = os.path.join('D:\\Hearthstone\\Replays\\', 'match9999') #**Destination needs to be the newest folder and I dont know how to implement that...
extmove = 'png' # The extension you wish to organize.
num = 0 # Variable simply to use after to count images.
for filename in os.listdir(folder): #Run through folder.
extension = filename.split(".")[-1] # This strips the extensions ready to check and places into the extension
if extension == extmove: # If statement. If the extension of the file matches the one set previously then..
shutil.move(folder + "\\" + filename, destination) # Move the file from the folder to the destination folder. Also previously set.
num = num + 1
print(num)
print (filename, extension)
And that's it! I need help with step 2.2. I'd certainly appreciate the help!
Now, the reason I made such a big post is because I wanted to expose my idea and hopefully inspire someone to take on a similar project seriously. Hearthstone has thousands of players that could benefit from it, not to mention that this seems to be a fairly easy task to someone with more experience.
Ok, I finally got it to work!
import sys
import os
import shutil
def sendPhotos():
matchNumber=1
photos_dest = "D:\\Hearthstone\\Replays\\Match"
while os.path.exists(photos_dest+ str(matchNumber)): #creates the name of the folder "Match1", "Match2", etc.
matchNumber=matchNumber + 1
else:
photos_destination = photos_dest+str(matchNumber)
os.makedirs(photos_destination)
for files in os.listdir('C:\\Users\\Felipe\\Desktop'):#only png files are moved
if files.endswith(".png"):
shutil.move(files, photos_destination)
sendPhotos()
Thank you to those who gave me some answers! I really appreciated it!
Well, first off, the fact that you identified a problem and put together a solution shows that you certainly don't lack programming skills. Give yourself some credit. You just need more practice. :)
This should be better, I haven't run it, so there might be some errors :P
def checkFunction(base_dir='D:\\Hearthstone\\Replays\\'): #set this as a parameter with a default
match_number = 1
if os.path.exists(base_dir): #if the base directory doesn't exist you'll have a bad time
while os.path.exists(os.path.join(base_dir, 'Match{0}'.format(match_number)))
match_number += 1
new_dir = os.path.join(base_dir, 'Match{0}'.format(match_number))
os.makedirs(new_dir)
return new_dir
For the function checkFolder, I suggest having it return the new directory name (as above). You'll also need to indent all the lines below it so python knows those lines are part of that function (this might just be a formatting issue on SO though).
Then, once the checkFolder function is working properly, all you have the change in 2.2 is:
destination = checkFolder()
This sees which matches are in the folder and takes the lowest number for the folder.
folder = os.path.join('C:\\Users\\Felipe\\', 'Desktop') # Folder in which the images are in.
recorded_matches_location = 'D:\\Hearthstone\\Replays\\'
match_number = 1
match_name = 'match1'
while match_name in os.listdir(recorded_matches_location):
match_number = 1 + match_number
match_name = 'match' + str(match_number) # corrected it! there must be a string and not a variable
destination = os.path.join(recorded_matches_location, match_name) #**Destination needs to be the newest folder and I dont know how to implement that...
extmove = 'png' # The extension you wish to organize.
num = 0 # Variable simply to use after to count images.
for filename in os.listdir(folder): #Run through folder.
extension = filename.split(".")[-1] # This strips the extensions ready to check and places into the extension
if extension == extmove: # If statement. If the extension of the file matches the one set previously then..
shutil.move(folder + "\\" + filename, destination) # Move the file from the folder to the destination folder. Also previously set.
num = num + 1
print(num)
print (filename, extension)