Python saving into specific directory based on user input - python

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

Related

Keep prompting user for correct directory to file, store input in variable

This is the beginning of my code that takes a dataset and plots it using matplotlib. However, I want to create a while loop that prompts the user to provide the correct path or directory to the file (e.g. /Users/Hello/Desktop/file.txt).
While the user does not inputs a correct path, the loop should keep prompting for a directory.
If there is indeed a file in that path, it should store this input in the variable path, which is later used to display the data.
If there is no file, it should ask it again.
It seems that my while loop is stuck at the first print statement..
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import itertools
import os
# This is the correct directory: os.path.isfile('/Users/Hello/Desktop/file.txt')
"""
Prompt the user for the right directory to the file.
If the file is not there, ask again.
If the path is correct, store it in the variable Path.
"""
correct = os.path.isfile(directory)
directory = input("Please provide the correct directory to the dataset ")
while os.path.isfile == False:
if os.path.isfile(Directory) != True:
directory = ath
print('Thank you')
elif os.path.isfile(Directory) == True:
print("This directory does not exist, please try again.")
#this variable inserts the users input and displays the data in the file
dframe = pd.read_table(path, delim_whitespace=True, names=('X','Y'),
dtype={'X': np.float64, 'Y':np.float64})
dframe.head(10) # show the first 10 rows of the data
Write a function. Your code has multiple problems, but I guess you want something like this.
def prompt_for_filepath():
"""
Prompt the user for the right path to the file.
If the file is not there, ask again.
If the path is correct, return it.
"""
while True:
path = input("Please provide the correct path to the dataset")
if os.path.isfile(path):
return path
print("This path does not exist, please try again.")
The code that sample that you posted is not syntactically correct.
The while block should not be indented compared to the preceding line.
directory is used before it is defined
To answer your question directly, after print('Thank you'), you need to have a break statement to break out of the while loop.
Your while loop invariant is also incorrect-- you're checking if os.path.isfile is False. os.path.isfile is a function and functions are truthy. You effectively wrote while True:-- this isn't incorrect, but it's not doing what you probably think it's doing.

How can I design a function which opens a folder based on user input, picks files with certain title format, and then reads specific lines from them?

I am having a moment of complete brain freeze right now and cannot seem to figure out how to design a code that will perform a series of tasks in one function. Basically, I want to design a code that asks the User for the input of a name of a folder in the working directory. The folders will have a 6 digit number for their name (for this example, let's assume the number of the folder is 111234). Once the folder is specified, certain files inside said folder will be opened and read. These files will be selected based on how their filenames are formatted, which is
(foldername)_(filenumber)_0_structure.in
wherein, for this example, the foldername is 111234 and the filenumber represents the order that the file appears in within the folder (can be the number zero or higher). The other terms in the filename (such as the zero after the filenumber), the word "structure", and the .in file extension are all constant. After all files that conform to this format are selected and opened, I want the 2nd and 3rd lines of these files to be read and copied into a dict whose keys are the file's filenumber and whose values contain a list of strings (i.e. the 2nd and 3rd lines).
So far, I have written the following in order to address these needs:
import os
from os import path
import re
def folder_validation(foldername):
folder_contents= {}
while True:
try:
foldername= str(raw_input(foldername))
file_path= path.join(current_directory, foldername)
except IOError:
print("Please give the name of a folder that exists in the current working directory.")
continue
for filename in os.listdir(file_path):
if re.search("{}_{}_0_detect1.in".format(foldername,[0*]), filename):
file_contents= str(open(filename).readlines()[2:3])
folder_contents[filenumber]= file_contents
return folder_contents
folder_input= folder_validation("Please give the name of the relevant folder you wish to analyze:")
The most obvious problem with the above code is that I am not sure how to format the regular expression search to include the user's input and the placement of any integer number in the filenumber variable. Additionally, the raw_input does not seem to be working. Any assistance would be most appreciated.
There were two main problems in my code: the first problem was that I did not properly configure the while loop condition and so the code would get stuck. The second problem was that I did not set up the filepath to my files in my folder correctly, and as a result, my code could not open the files and read them. The regex line was also improved to include any filenames that had numbers 0 and above be read (in the specified format). The corrected version of the code is posted below.
import os
from os import path
import re
def folder_validation(foldername):
folder_contents= {}
while True:
try:
foldername= str(raw_input(foldername))
file_path= path.join(current_directory, foldername)
except IOError:
print("Please give the name of a folder that exists in the current working directory.")
continue
else:
break
while True:
for filename in os.listdir(file_path):
if re.search("{}_[0-9]+_0_detect1.in".format(foldername,[0*]), filename):
file_contents= open(path.join(file_path,filename))
file_lines= file_contents.readlines()[2:3]
folder_contents[filename]= file_lines
return folder_contents
folder_input= folder_validation("Please give the name of the relevant folder you wish to analyze:")

Editing Paths in Python

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'

Trying to create a replay feature for a Turn-based game (very newbie)

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)

How to confirm only html files exist in a given folder and if not then how to prompt the user to specify a folder with only html files within

I would like to create a python script that will do 3 things: 1) Take user input to navigate to a file directory2) Confirm the file contents (a particular set of files need to be in the folder for the script to proceed)3) Do a Find and Replace
The Code as of now:
import os, time
from os.path import walk
mydictionary = {"</i>":"</em>"}
for (path, dirs, files) in os.walk(raw_input('Copy and Paste Course Directory Here: ')):
for f in files:
if f.endswith('.html'):
filepath = os.path.join(path,f)
s = open(filepath).read()
for k, v in mydictionary.iteritems(): terms for a dictionary file and replace
s = s.replace(k, v)
f = open(filepath, 'w')
f.write(s)
f.close()
Now i Have parts 1 and 3, I just need part 2.
for part 2 though I need to confirm that only html files exist in the directory the the user will specified otherwise the script will prompt the user to enter the correct folder directory (which will contain html files)
Thanks
From what I understand, here's your pseudocode:
Ask user for directory
If all files in that directory are .html files:
Do the search-and-replace stuff on the files
Else:
Warn and repeat from start
I don't think you actually want a recursive walk here, so first I'll write that with a flat listing:
while True:
dir = raw_input('Copy and Paste Course Directory Here: ')
files = os.listdir(dir)
if all(file.endswith('.html') for file in files):
# do the search and replace stuff
break
else:
print 'Sorry, there are non-HTML files here. Try again.'
Except for having the translate the "repeat from start" into a while True loop with a break, this is almost a word-for-word translation from the English pseudocode.
If you do need the recursive walk through subdirectories, you probably don't want to write the all as a one-liner. It's not that hard to write "all members of the third member of any member of the os.walk result end with '.html'", but it will be hard to read. But if you turn that English description into something more understandable, you should be able to see how to turn it directly into code.

Categories

Resources