So I'm making a sudoku game wherein I should get the board of the game from a file (the given numbers) and there should be many files to choose from.
I can only think of is:
if choice==1:
sudoku=open(file1, "r+")
and so on but it would take many lines by just opening a file.
Is there a way to open random file in python3?
If you want to open a file based on user input, you are looking to format strings, using str.format.
Let's say the user choice is choice, and each file is labeled as game1, game2, game3, etc. That is, the Sudoku game for choice is prepended by game.
To get the path of the file, you want to use
path = "game{number}".format(number = choice)
Then, just open it as usual. Putting it all together:
choice = int(input("Enter a file number: "))
path = "game{number}".format(number = choice)
sudoku = open(path, "r+")
You could theoretically put several filenames into a list, then use the random.choice() method. Here's the code:
listOfFiles = [file1, file2, file3]
selectedFile = random.choice(listOfFiles)
Then you can load and operate on the randomly chosen file.
Related
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())
So I'm currently using 'shelve' to save game data for a game I'm working on, however when I use pyinstaller to pack this game into an exe it creates 3 different file's all with the same name but different file types, even though when creating the file I don't specify a file type.
def save_game(yn):
if yn:
file = shelve.open('savegame', 'n')
file['map'] = map
file['objects'] = objects
file['player_index'] = objects.index(player) # index of player in objects list
file['stairs_index'] = objects.index(stairs) # same for the stairs
file['inventory'] = inventory
file['game_msgs'] = game_msgs
file['game_state'] = game_state
file['dungeon_level'] = dungeon_level
file.close()
this creates the save file with no file type (which works great!) however in exe form it creates 'savegame.bak', 'savegame.dir', and 'savegame.dat' when the player dies I call a function which saves the file (in case there is no save file) and then delete it, so you can't access your ended game save.
def player_death(player):
# the game ended!
global game_state
...
game_state = 'dead'
...
save_game(True)
os.remove('savegame')
In short I just need to know how I can make the os.remove line get rid of the savegame whether it's just 1 file or 3 different files all with different file types.
one option is to use pathlib.
from pathlib import Path
for file in Path("/path/to/dir/with/saves").glob('savegame.*') :
file.unlink()
if you can express it with wildcards, the glob module is for you.
from glob import iglob
for file in iglob("savegame.*"):
os.remove(file)
note: if you know that you will only match a few files, you can safely use glob instead of iglob. if you don't know how many files you will match, you should generally use iglob to not end up with a huge list in memory.
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
So i've been given a task to take 3 parameters from a user, and then do these tasks:
Search the folder given as input.
Find all of a certain file type extension.
Print this to another folder.
Is there an easier way of performing this task? Attempting to use os.listdir responds that it can't find the file, as it doesn't accept a variable as input.
Directories = [];
InitDirect = str(input('Please insert the file directory you want to search (C:\\x)'))
FileType = str(input('Please state a desired file type (.txt, .png)'))
OutDirect = str(input('Please state the output directory for the files.'))
for file in os.listdir("InitDirect"):
if file.endswith("FileType"):
print(os.path.join("InitDirect", file))
This is my current code, although likely incorrect. If anyone could help, that'd be great!
There is no need to use quotes around the variable names. Adding "" around the variable names actually declares strings and you are not using the value of the variable. Change the code to the following and it should work.
Directories = [];
InitDirect = str(input('Please insert the file directory you want to search (C:\\x)'))
FileType = str(input('Please state a desired file type (.txt, .png)'))
OutDirect = str(input('Please state the output directory for the files.'))
for file in os.listdir(InitDirect):
if file.endswith(FileType):
print(os.path.join(InitDirect, file))
Ok I'm going to try this again, apologies for my poor effort in my pervious question.
I am writing a program in Java and I wanted to move some files from one directory to another based on whether they appear in a list. I could do it manually but there a thousands of files in the directory so it would be an arduous task and I need to repeat it several times! I tried to do it in Java but because I am using Java it appears I cannot use java.nio, and I am not allowed to use external libraries.
So I have tried to write something in python.
import os
import shutil
with open('files.txt', 'r') as f:
myNames = [line.strip() for line in f]
print myNames
dir_src = "trainfile"
dir_dst = "train"
for file in os.listdir(dir_src):
print file # testing
src_file = os.path.join(dir_src, file)
dst_file = os.path.join(dir_dst, file)
shutil.move(src_file, dst_file)
"files.txt" is in the format:
a.txt
edfs.txt
fdgdsf.txt
and so on.
So at the moment it is moving everything from train to trainfile, but I need to only move files if the are in the myNames list.
Does anyone have any suggestions?
check whether the file name exists in the myNames list
put it before shutil.move
if file in myNames:
so at the moment it is moving everything from train to trainfile, but ii need to only move files if the are in the myName list
You can translate that "if they are in the myName list" directly from English to Python:
if file in myNames:
shutil.move(src_file, dst_file)
And that's it.
However, you probably want a set of names, rather than a list. It makes more conceptual sense. It's also more efficient, although the speed of looking things up in a list will probably be negligible compared to the cost of copying files around. Anyway, to do that, you need to change one more line:
myNames = {line.strip() for line in f}
And then you're done.