Load Email:Pass from a file - python

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

Related

check if a file is modified and print the modified line

i tried to make auto check if file is modified then print and send to discord using webhook, but it print the last line and before the last line. i just want to print the last line. here is the code
def readfile():
with open("test.txt", "r") as t:
read = t.readlines()
return read
before = readfile()
while True:
after = readfile()
if before != after:
for line in after:
if line not in before:
print(line)
sendembed()
before = after
im new to python, anyone can help me?
given that the first part is answered with the link: How do I watch a file for changes?
This will answer the second part, which the question was close on.
def readfile():
with open(`\test.txt`, "r") as t:
read = t.readlines()
return read
x = readfile()
# this is the last line
print( x[-1] )
The reason for this is that readlines() creates a list and the user can access the last element of the list.

How to prompt user that asks a user for a file name?

I am going through Intro to Programming so basic stuff here, I have an assignment to "write a program that asks a user for a file name and then displays the first 5 lines of the file," I just can't figure out how to use the input command in this situation and then transfer to open()
Edit: Sorry here is a code snippet I had, I just don't get how to apply input from here.
def main():
#This function writes to the testFile.docx file
outfile = open('testFile.docx', 'w')
outfile.write('Hello World\n')
outfile.write('It is raining outside\n')
outfile.write('Ashley is sick\n')
outfile.write('My dogs name is Bailey\n')
outfile.write('My cats name is Remi\n')
outfile.write('Spam Eggs and Spam\n')
outfile.close()
infile = open('testFile.docx', 'r')
testFileContent = infile.read()
infile.close()
print(testFileContent)
main()
First, we ask for a filename. Then we use the try clause, which checks whether the file exists. If it does it will print 5 lines. If it does not, it will print No such a file found!
x = input('Enter a file name')
try:
with open(x) as f:
data = f.readlines()
for i in range(5):
print(data[i])
except:
print('No such a file found!')
Using a simple function,
def hello_user():
user_input = input('Enter file name: ')
try:
with open(user_input, 'r') as f:
data = f.readlines()
data = data[:5]
for o in data:
print(o.strip())
except FileNotFoundError:
print('Not found ')
hello_user()
It asks for a file name
If the file exists in the same directory the script is running, it opens the file and read each lines (white lines inclusive)
We select only the first 5 lines
We iterate through the list and remove the extra whitespace character(e.g \n).
If the file was not found, we catch the exception.
input() is used to receive input from the user. Once we recieve the input, we use the open() method to read the file in read mode.
def main():
file = input("Please enter a file name")
with open(file, 'r') as f:
lines = f.readlines()
print(lines[:5])
The with statement makes sure that it closes the file automatically without explicitly calling f.close()
The method f.readlines() returns an array containing the lines in the file.
The print() statement prints the first 5 lines of the file.

How could I pass a list of files to a function and get the same list back with changes made to the files?

How can I send a list of files to a function, apply regex to the lines in each file in the list and return the new list? I can write the changes to a new file but don't know how to replace the files in the list and send it back. Here is my code:
def apply_regex(myList = [], *args):
for index, item in enumerate(myList):
file = open(myList[index], 'r')
out_file = open(myList[index] + ".regex", "w")
for line in file:
line = re.sub('some_regex',r'some_thing_to_sub', line)
out_file.write(line)
Function call:
listFile=['file1', 'file2', 'file3']
apply_regex(listFile)
#take some action on listFile based on the new values#
But I can't pass the new values from the function! I know I have to write to the files within the def apply_regex but need help doing it and then passing it back.
If you literally want to replace the items in the original list:
def apply_regex(myList = [], *args):
for index, item in enumerate(myList):
file = open(myList[index], 'r')
out_file = open(myList[index] + ".regex", "w")
myList [index] += ".regex"
for line in file:
line = re.sub('some_regex',r'some_thing_to_sub', line)
out_file.write(line)
out_file.close () # Flush buffer

Using python to read txt files and answer questions

a01:01-24-2011:s1
a03:01-24-2011:s2
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
So I have this list of data as a txt file, where animal name : date : location
So I have to read this txt file to answer questions.
So so far I have
text_file=open("animal data.txt", "r") #open the text file and reads it.
I know how to read one line, but here since there are multiple lines im not sure how i can read every line in the txt.
Use a for loop.
text_file = open("animal data.txt","r")
for line in text_file:
line = line.split(":")
#Code for what you want to do with each element in the line
text_file.close()
Since you know the format of this file, you can shorten it even more over the other answers:
with open('animal data.txt', 'r') as f:
for line in f:
animal_name, date, location = line.strip().split(':')
# You now have three variables (animal_name, date, and location)
# This loop will happen once for each line of the file
# For example, the first time through will have data like:
# animal_name == 'a01'
# date == '01-24-2011'
# location == 's1'
Or, if you want to keep a database of the information you get from the file to answer your questions, you can do something like this:
animal_names, dates, locations = [], [], []
with open('animal data.txt', 'r') as f:
for line in f:
animal_name, date, location = line.strip().split(':')
animal_names.append(animal_name)
dates.append(date)
locations.append(location)
# Here, you have access to the three lists of data from the file
# For example:
# animal_names[0] == 'a01'
# dates[0] == '01-24-2011'
# locations[0] == 's1'
You can use a with statement to open the file, in case of the open was failed.
>>> with open('data.txt', 'r') as f_in:
>>> for line in f_in:
>>> line = line.strip() # remove all whitespaces at start and end
>>> field = line.split(':')
>>> # field[0] = animal name
>>> # field[1] = date
>>> # field[2] = location
You are missing the closing the file. You better use the with statement to ensure the file gets closed.
with open("animal data.txt","r") as file:
for line in file:
line = line.split(":")
# Code for what you want to do with each element in the line

How to Open a file through python

I am very new to programming and the python language.
I know how to open a file in python, but the question is how can I open the file as a parameter of a function?
example:
function(parameter)
Here is how I have written out the code:
def function(file):
with open('file.txt', 'r') as f:
contents = f.readlines()
lines = []
for line in f:
lines.append(line)
print(contents)
You can easily pass the file object.
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable.
and in your function, return the list of lines
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
Another trick, python file objects actually have a method to read the lines of the file. Like this:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
With the second method, readlines is like your function. You don't have to call it again.
Update
Here is how you should write your code:
First method:
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable (list).
print(contents)
Second one:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
print(contents)
Hope this helps!
Python allows to put multiple open() statements in a single with. You comma-separate them. Your code would then be:
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)
def fun(file):
contents = None
with open(file, 'r') as fp:
contents = fp.readlines()
## if you want to eliminate all blank lines uncomment the next line
#contents = [line for line in ''.join(contents).splitlines() if line]
return contents
print fun('test_file.txt')
or you can even modify this, such a way it takes file object as a function arguement as well
Here's a much simpler way of opening a file without defining your own function in Python 3.4:
var=open("A_blank_text_document_you_created","type_of_file")
var.write("what you want to write")
print (var.read()) #this outputs the file contents
var.close() #closing the file
Here are the types of files:
"r": just to read a file
"w": just to write a file
"r+": a special type which allows both reading and writing of the file
For more information see this cheatsheet.
def main():
file=open("chirag.txt","r")
for n in file:
print (n.strip("t"))
file.close()
if __name__== "__main__":
main()
the other method is
with open("chirag.txt","r") as f:
for n in f:
print(n)

Categories