How to have a variable that changes its name after every loop? - python

So basically I want to create a variable that changes after every iteration of a for loop to be the same as the search term that is used in the for loop in question, is that possible? I explained better in the code I think.
with open ('lista1.txt','r') as file_1:
reader_0 = file_1.readlines() # Reads a list of searchterms,
# the first search term of this list is "gt-710".
for search in reader_0:
file_0 = search.replace("\n","") +".txt"
file_1 = str(file_0.strip())
try: #if the file named the same as the searchterm exists, read its contents
file = open(file_1,"r")
search = file.readlines() # How do I create a variable that
# changes names? for example I want the
# content of file readlines be saved in
# a variable called the same as the
# searchterm in this ase I want it to
# be gt-710 = file.readlines()...in the
# next iteration I want it to be
# next_search_term_in_the_list =
# file.readlines()..an so on...
print(str(search) + "I actually tried")
except: #if not, create it
file = open(file_1,"w")
file.write("hello")
print("I didnt")
file.close()

This is impossible in Python, but you can do something similar. Enter stage left, the DICTIONARY! A dictionary is like a list, but you set your own keys. Make it like this:
my_dict = {}
You can add to the dictionary like so:
my_dict["key"] = "value"
A way you could implement this into your code could be as follows:
the_dict = {}
with open ('lista1.txt','r') as file_1:
[...]
file = open(file_1,"r")
file_contents = file.readlines()
the_dict[search] = file_contents
print(str(file_contents) + "I actually tried")
[...]

Related

Load Email:Pass from a file

file = open("list.txt", "r", encoding="Latin-1").readlines()
file = [combos.rstrip() for combos in file]
for lines in file:
data = lines.split(":")
password = data[1]
email = data[0]
print(email)
my list.txt looks like this:
test#gmail.com:Password1
123#gmail.com:Pass
842398412#Gmail.com:daidn
Output:
842398412#Gmail.com
I want it to move down to the next line each time I call email so, for example,
if I do print(email) I want it to output the first email in the list and if I call it again I want to output the second one. Is this possible?
To look for the next line when running your code again, your code needs to keep track of what line it should be looking for. You can write a generator that keeps track of this for you, and you can call next() to get each next value in the list.
def file_lines():
lines = open("list.txt", "r", encoding="Latin-1").readlines()
for line in lines:
yield line
generator = file_lines()
print(next(generator))
print(next(generator))
print(next(generator))
Alternatively just store it in a list and don't use a generator at all
My recommendations:
Don't recommended to open files without context managers
You can do a function yield...
You can convert a list to an iter.
I prefer last:
with open("list.txt", "r", encoding="Latin-1") as file:
content = [i.rstrip() for i in file.readlines()]
for lines in content:
data = lines.split(":")
password = data[1]
email = data[0]
items.append(email)
emails = iter(items)
And then next(email) for iterate above it
Good luck

Appending the correct values from a list

I am making an Instagram bot and I store the names of the users that the bot has followed in file.txt.
unique_photos = len(pic_hrefs) # TODO Let this run once and check whether this block of code works or not
followers_list = [] # Contains the names of the people you followed
for pic_href in pic_hrefs:
driver.get(pic_href)
sleep(2)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
try:
# Like this picture
driver.find_element_by_xpath("//*[#aria-label='Like']").click()
print("Picture liked") # TODO After checking delete this line
follow_button = driver.find_element_by_class_name('bY2yH')
# Follow the user if not followed already
if follow_button.text == "•\n" + "Follow":
follow_button.click()
followed = driver.find_element_by_class_name('e1e1d')
followers_list.append(followed.text)
with open("file.txt", 'a') as file:
file.write(",".join(followers_list))
file.write(",")
else:
continue
for second in reversed(range(0, 3)):
print_same_line("#" + tag + ': unique photos left: ' + str(unique_photos)
+ " | Sleeping " + str(second))
sleep(1)
except Exception:
sleep(2)
unique_photos -= 1
This is the final result in the file.txt:
kr.dramas_,kr.dramas_,marcelly.lds,kr.dramas_,marcelly.lds,espn
It's clear that the problem is that as I append the whole followers_list (which contains all the usernames of the people the bot followed) the names repeat. So I need a way to only append the new names.
And I know that I can just change the code to 'w' to create a whole new file every time but that creates a problem because after I stop the bot and if I don't unfollow the users from that list and start the bot again I will lose all the names from the file, which I don't want.
So I need suggestions so that after the bot is stopped the file.txt looks like this:
kr.dramas_,marcelly.lds,espn,
I would suggest that once you've followed everyone, you can read all of the names from the file into a list/set and then add names that aren't in the list/set into it. Then simply overwrite the old file.
followers_list = [] # will be populated with follower names
with open("file.txt", 'r') as file:
file_names = file.readline().split(",")
for follower in followers_list:
if follower not in file_names:
file_names.append(follower)
with open("file.txt", 'w') as file:
file.write(",".join(file_names))

adding a value to a set in a dictionary

def CreateDataBaseByActor(file):
dataBase = dict()
set = {}
f = open(file,"r")
for line in f:
set = line.split(', ')
for movie in set[1:]:
dataBase[movie] = set[0]
return dataBase
i have a file that each line is written by the format: actor_name, movie1, movie2, movie3...
example:
Sylvester Stallone, Rocky, Rambo, Assassins
Julianne Moore, Assassins, Hannibal
the problem is that when i try to add to a movie, another actor name (for example: in the first line, the key - Assassins- has the value Sylvester Stallone, and in the second line value of - Assassin - is replaced instead of added)
Assuming you want to return a dictionary that maps movie titles to a list of actors within each (which isn't clear from the name of the function), then this code should do it for you. (Note that I changed the variable named set to be called fields since it's not a good idea to name variables after types.)
def CreateDataBaseByActor(file):
dataBase = dict()
f = open(file, "r")
for line in f:
fields = line.split(', ')
actor = fields[0]
for movie in fields[1:]:
dataBase.setdefault(movie, []).append(actor)
return dataBase

How to open multiple files without repeating the code

I am making a program that will open multiple files, they are all very similar. All contains a few one word lines in lowercase on Notepad. I do not want to repeat the code multiple times. Ideally I want to use a while loop to repeat the code but change what file it opens each repeat. Is there a way to do it?
This is the current code:
File = open("Key Words\Audio.txt","r") #This will open the file called Audio.
Audio = [] #This creates the Audio list
Audio = File.read().splitlines() #This saves everything on each line of the Audio file to a diffrent section of the Audio list.
File = open("Key Words\Calls.txt","r") #This will open the file called Calls.
Calls = [] #This creates the Calls list
Calls = File.read().splitlines() #This saves everything on each line of the Calls file to a diffrent section of the Calls list.
File = open("Key Words\Charging.txt","r") #This will open the file called Charging.
Charging = [] #This creates the Charging list
Charging = File.read().splitlines() #This saves everything on each line of the Charging file to a diffrent section of the Charging list.
File.close() #This closes the File(s).
This is what functions are for:
def readfile(filepath):
with open(filepath, 'r') as f:
return f.read().splitlines()
audio = readfile('Key Words\Audio.txt')
calls = readfile('Key Words\Calls.txt')
charging = readfile('Key Words\Charging.txt')
Make a list of the files you need to open:
files_to_open = [
'file_1.txt',
'file_2.txt'
]
calls_info = {}
Iterate over the list, and open and process:
for file_ in files_to_open:
with open(file_) as f:
calls_info[file_] = f.read().splitlines()
Here, I created a calls_info variable. What this will do is store everything in a dictionary. These hold keys and values - to access the value of a file, simply index it like so:
calls_info[file_path] # Make sure file_path is the right path you put in the list!
Put the code in a function:
def openandread(filename):
# No need to close the file if you use with:
with open(filename,"r") as File:
return_this = File.read().splitlines()
return return_this
and then just call this function multiple times:
Audio = openandread("Key Words\Audio.txt")
Calls = openandread("Key Words\Calls.txt")
Charging = openandread("Key Words\Charging.txt")
or if you want to make it even shorter:
Audio, Calls, Charging = (openandread(i) for i in ["Key Words\Audio.txt", "Key Words\Calls.txt", "Key Words\Charging.txt"])
Try this
Audio = []
Calls = []
Charging = []
FILES_LISTS = (
( "Key Words\Audio.txt", Audio ),
( "Key Words\Calls.txt", Calls ),
( "Key Words\Charging.txt", Charging )
)
for file_name, list_var in FILES_LISTS:
File = open( file_name, 'r' )
list_var += File.read().splitlines()
File.close()
Make sure to type list_var += and not list_var =. This works because lists are mutable and because python works with references.
You can try unipath
# Install
$easy_install unipath
# In python
from unipath import Path
t1 = Path('Key Words\Audio.txt')
...

How should I replace parts from a text file through Python?

Okay, so here's the deal, folks:
I've been experimenting with Python(3.3), trying to create a python program capable of generating random names for weapons in a game and replacing their old names, which are located inside a text file. Here's my function:
def ModifyFile(shareddottxt):
global name
a = open(str(shareddottxt) , 'r')
b = a.read()
namefix1 = '''SWEP.PrintName = "'''
namefix2 = '''" //sgaardname'''
name1 = b.find(namefix1) + len(namefix1)
name2 = b.find(namefix2, name1)
name = name + b[name1:name2] ## We got our weapon's name! Let's add the suffix.
c = open((shareddottxt + ".lua"), 'r+')
for line in b:
c.write(line.replace(name, (name + namesuffix)))
c.close()
a.close
As you can see, I first open my text file to find the weapon's name. After that, I try to create a new file and copy the contents from the old one, while replacing the weapon's name for (name + namesuffix). However, after calling the function, I get nothing. No file whatsoever. And even if I DO add the file to the folder manually, it does not change. At all.
Namesuffix is generated through another function early on. It is saved as a global var.
Also, my text file is huge, but the bit I'm trying to edit is:
SWEP.PrintName = "KI Stinger 9mm" //sgaardname
The expected result:
SWEP.PrintName = "KI Stinger 9mm NAMESUFFIX" //sgaardname
Where did I mess up, guys?
Something like this is more pythonic.
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r+') as file:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
file.seek(0)
file.write(new_lines)
If you don't want to replace that file
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r') as file, open(filename + ".temp", 'w') as temp:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
temp.write(new_lines)

Categories