The my_data.txt file looks like this:
jim#gmail.com: hello123
tim#gmail.com: hello1234
The program actually extracts the email address and password from the my_data.txt file really intelligently for a basic programmer at least. But each time I run it, it yells ValueError: substring not found, even thou I tried both the string methods: .index() and .find().
file = open('my_data.txt', 'r')
for line in file.readlines():
break_line = line.index(':') # OR: break_line = line.find(':')
email = line[:break_line]
password = line[(break_line + 2):len(line)]
print(line.find(':'))
I expect you got empty lines in your text file. Try skipping empty lines and lines that do not contain ":" at the beginning:
for line in file.readlines():
if not line.strip():
continue
if ":" not in line:
continue
break_line = line.index(':') # OR: break_line = line.find(':')
email = line[:break_line]
password = line[(break_line + 2):len(line)]
print(line.find(':'))
Maybe you can try this code:
for line in file.readlines():
if line.strip(): # meaning there is a valid line
print(line)
break_line = line.split(':') #index(':') # OR: break_line = line.find(':')
email = break_line[0]
print(email)
password = break_line[1]
print(password)
Related
I'm working on a Python course on Coursera. One of the assignments is to read input from a text file, extract the email addresses on lines starting with "From:", and then print both email addresses and the number of lines that start with "From:". I got it to work after a little effort, but I wanted to see if my code can be cleaned up.
If I shouldn't worry so much about writing elegant code if I'm just in my second week of Python, you can go ahead and let me know.
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
text = fh.read()
lines = text.splitlines()
count = 0
from_lines = list()
for line in lines:
if 'From:' in line:
count += 1
from_lines.append(line)
email = list()
for line in from_lines:
email = line.split()
print(email[1])
print("There were", count, "lines in the file with From as the first word")
You can get the work done with only one loop like this:
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
lines = text.readlines() #readlines creates a list of lines from the file
count = 0
for line in lines:
if 'From:' in line:
count += 1
email = line.split()[1]
print(email)
fh.close() # always close the file after use
print("There were {} lines in the file with From as the first word".format(count))
You never close the file. Anyway you shouldn't be handling the files manually, and instead use a context manager:
with open(fname) as as fh:
...
If you are going to iterate the file line-by-line, there is no need to save to memory the whole content of the file to a string. Files are iterators themselves and iterating over them gives the lines:
for line in fh:
There is no need for two loops - if you just found there is an email in a line, why save it for later? Just use it right there!
You might check if the line startswith instead of using in.
All together might give:
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
count = 0
with open(fname) as fh:
for line in fh:
if line.startswith('From:'):
count += 1
email = line.split()[1]
print(email)
print("There were", count, "lines in the file with From as the first word")
Here:
fname = input("Enter file name: ")
if not(fname): fname = "mbox-short.txt"
with open(fname) as fh:
lines = fh.readlines()
count = 0
from_lines = [line for line in lines if line.startswith('From:')]
for line in from_lines:
count += 1
email = line.split()
print(email[1])
print("There were",count,"lines in the file with From as the first word")
Or...
fname = input("Enter file name: ")
if not(fname): fname = "mbox-short.txt"
with open(fname) as fh:
lines = fh.readlines()
from_lines = [line for line in lines if line.startswith('From:')]
for line in from_lines: print(line.split()[1])
print(f"There were {len(from_lines)} lines in the file with From as the first word")
I have a password file containing different username and associated password for that user
$ cat /apps/test_lab/.passwd
amon: abc#321
bmon: dgf#869
cmon: ascd#!!#657
What I am trying to do is get the password by searching in a file using the username and store it in a variable
text = "cmon"
pswd_file = open("/apps/test_lab/.passwd", "r")
for line in pswd_file:
if re.match('(.+)' +text+ '(.+)', line):
print line
I am getting output as:
cmon: ascd#!!#657
While I want output like:
pswd_user="ascd#!!#657"
Can you help me with this? I am running as python 2.7.5.
i tried a solution like:
import re
for line in open('/apps/test_lab/.passwd').readlines():
line = line.strip()
matchobj = re.match('^\s*(\w+)\:\s+(.*)$',line)
username, password = matchobj.group(1,2)
if username == 'cmon':
print('pswd_user="'+password+'"')
You need to split(':') with ':' and strip() to remove white spaces at both ends
import re
text = "cmon"
pswd_file = open("testing.txt", "r")
for line in pswd_file:
if re.match('(.+)' +text+ '(.+)', line):
pwd = line.split(':')[1]
pwd = pwd.strip()
print('pswd_user="'+ pwd +'"')
The script is adding a line break right after the curly braces while writing both strings right after the username. I would think this is because of my source text file has encoding in it adding the breaks but as far as I can tell it does not. Am I misunderstanding how write works? Something simple I'm missing. Been looking at this too long and need a new set of eyes.
users_list = []
users = input("File of User's ")
user_file = open(users + '.txt', 'r')
for i in user_file:
users_list.append(i)
sql_file = open('sql.txt', 'w')
sql_file.write("SELECT MACHINE.NAME AS SYSTEM_NAME, SYSTEM_DESCRIPTION,
MACHINE.IP, MACHINE.MAC, MACHINE.ID as TOPIC_ID FROM MACHINE WHERE
((MACHINE.USER_NAME = '{}') OR ".format(users_list[0]))
for i in users_list:
sql_file.write("(MACHINE.USER_NAME = '{}')".format(i))
sql_file.write(" OR ")
The output of the file looks like this:
SELECT MACHINE.NAME AS SYSTEM_NAME, SYSTEM_DESCRIPTION, MACHINE.IP, MACHINE.MAC, MACHINE.ID as TOPIC_ID FROM MACHINE WHERE ((MACHINE.USER_NAME = 'hnelson
') OR (MACHINE.USER_NAME = 'hnelson
') OR (MACHINE.USER_NAME = 'snery
') OR (MACHINE.USER_NAME = 'jherman
change your line 7 and 8
for i in user_file:
users_list.append(i)
to
for i in user_file:
users_list.append(i.strip())
and it should work as expected.
It is because i is a line from user_file and it ends with \n. i.strip() removes the trailing newline.
Here is what I am trying to do:
I am trying to solve an issue that has to do with wrapping in a text file.
I want to open a txt file, read a line and if the line contains what I want it to contain, check the next line to see if it does not contain what is in the first line. If it does not, add the line to the first line.
import re
stuff = open("my file")
for line in stuff:
if re.search("From ", line):
first = line
print first
if re.search('From ', handle.next()):
continue
else: first = first + handle.next()
else: continue
I have looked a quite a few things and cannot seem to find an answer. Please help!
I would try to do something like this, but this is invalid for triples of "From " and not elegant at all.
lines = open("file", 'r').readlines()
lines2 = open("file2", 'w')
counter_list=[]
last_from = 0
for counter, line in enumerate(lines):
if "From " in line and counter != last_from +1:
last_from = counter
current_count = counter
if current_count+1 == counter:
if "From " in line:
counter_list.append(current_count+1)
for counter, line in enumerate(lines):
if counter in counter_list:
lines2.write(line)
else:
lines2.write(line, '\n')
Than you can check the lines2 if its helped.
You could also revert order of lines, then check in next line not in previous. That would solve your problem in one loop.
Thank you Martjin for helping me reset my mind frame! This is what I came up with:
handle = open("my file")
first = ""
second = ""
sent = ""
for line in handle:
line = line.rstrip()
if len(first) > 0:
if line.startswith("From "):
if len(sent) > 0:
print sent
else: continue
first = line
second = ""
else:
second = second + line
else:
if line.startswith("From "):
first = line
sent = first + second
It is probably crude, but it definitely got the job done!
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()