Python forloop only returning last line - python

Below is my current code. It's supposed to read in a file, compare the regex and see if the input from the text file is a correct IPv4 address or not. It is working correctly, however only returning the output for the last line of the input file. For example, if the input file looks like:
10.0.0.0
255.255.255.255
168.192.0.0
it will only return that 168.192.0.0 is correct. not any of the other addresses. Thank you.
**
import re
filename = input("Please enter the name of the file containing the input IP Addresses: ")
fo = open(filename, "r")
print()
for line in open(filename):
pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
m = re.match(pattern, line)
if m is not None:
print("Match found - valid IP address: ", line, "\n")
else: print("Error - no match - invalid IP address: ",line, "\n")
fo.close

You need to put your regex matching within the for loop :
for line in open(filename):
pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
m = re.match(pattern, line)
if m is not None:
print("Match found - valid IP address: ", line, "\n")
else: print("Error - no match - invalid IP address: ",line, "\n")
fo.close

The print and re.match are outside the loop, hence only the last iteration gets printed
for line in open(filename):
pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
m = re.match(pattern, line)
if m is not None:
print("Match found - valid IP address: ", line, "\n")
else: print("Error - no match - invalid IP address: ",line, "\n")

going to want to make a few formatting changes, better to open files with with.
import re
filename = input("Please enter the name of the file containing the input IP Addresses: ")
with open(filename) as fo:
print()
pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
for line in open(filename):
if re.search(r"%s"%(pattern), line):
print("Match found - valid IP address: ", line, "\n")
else: print("Error - no match - invalid IP address: ",line, "\n")

Related

Python3 Regex Split Issues (Splitting by IP Address [duplicate]

I wrote some code to extract email and IP addresses from bulk text. However, the code extracts only the email addresses. (The original text, which I would like to make understandable, is a typical log file). I don't know why the generated file does not give me back the IP addresses.
import os
import re
# 1
filename = 'errors.txt'
newfilename = 'emaillist-rev.txt'
# 2
if os.path.exists(filename):
data = open(filename,'r')
bulkemails = data.read()
else:
print "File not found."
raise SystemExit
# 3
r = re.compile(r'[\w\.-]+#[\w\.-]+')
results = r.findall(bulkemails)
emails = ""
for x in results:
emails += str(x)+"\n"
# 4
ip = re.compile('^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
result = ip.findall(bulkemails)
ip =""
for y in result:
ip += str(y)+"\n"
# 5
def writefile():
f = open(newfilename, 'w')
f.write(emails + ip)
f.close()
print "File written."
# 6
def overwrite_ok():
response = raw_input("Are you sure you want to overwrite "+str(newfilename)+"? Yes or No\n")
if response == "Yes":
writefile()
elif response == "No":
print "Aborted."
else:
print "Please enter Yes or No."
overwrite_ok()
# 7
if os.path.exists(newfilename):
overwrite_ok()
else:
writefile()
When declaring the ip regex, replace the anchors with word boundaries and mind you need to use a raw string literal.
ip = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')

How to find a certain string/name in a txt file?

So im making a name generator/finder, So for the find command i want to find that name in the txt file with the line number! So how do i find the name with the line number?
line = 0
names = open(r"names.txt", "r")
name1 = names.readlines()
uname = input("Please enter the name you want to find: ")
for name in name1:
try:
print(name)
print(line)
if name == uname:
print(f"Found name: {name} \nLine No. {line + 1}")
else:
line = line + 1
except:
print("Unable to process")
But it seems to not work except if you write the last name in file it works. So could give any help?
EDIT: Ive found a way so you can reply if you want to for further people running into the problem!
Try this:
with open("names.txt", "r") as f:
file_contents = names.read().splitlines()
uname = input("Please enter the name you want to find: ")
for line, row in enumerate(file_contents):
if uname in row:
print('Name "{0}" found in line {1}'.format(uname, line))
Yo
if "namefilled" in name :
print("found it")
You can use pathlib if you have Python 3.4+. Pretty handy library.
Also, context management is useful.
# Using pathlib
from pathlib import Path
# https://docs.python.org/3/library/fnmatch.html?highlight=fnmatch#module-fnmatch
import fnmatch
# Create Path() instance with path to text file (can be reference)
txt_file = Path(r"names.txt")
# Gather input
uname = input("Please enter the name you want to find: ")
# Set initial line variable
line = 0
find_all = False
# Use context maangement to auto-close file once complete.
with txt_file.open() as f:
for line in f.readlines():
# If python 3.8, you can use assignment operator (:=)
if match_list := fnmatch.filter(line, uname) is not None: # Doe not match substring.
number_of_names = len(match_list)
name_index = [i for i, element in enumerate(line.split()) for word in match_list if word == element]
print(f"""
{number_of_names} name{"s" if number_of_names > 0 else ""} found on line {line} at position {name_index}.
""".strip())
line += 1
Edited to include fnmatch per some other comments in this thread about matching the full string vs. a substring.
You could try something like this:
import re
search_name = input("Enter the name to find: ")
with open("names.txt", "r") as f:
for line, row in enumerate(f.read().splitlines()):
if re.findall('\\b'+search_name+'\\b', row, flags=re.IGNORECASE):
print('Name "{0}" found in line {1}'.format(search_name, line))
You can remove the flags=re.IGNORECASE flag in case you want the seaarch to be case-sensetive.

How do I split text from a text file at newlines?

I need to encrypt a message. The message follows, it is saved in a file named assignmenttest.txt
Hi my name is Allie
I am a Junior
I like to play volleyball
I need the program to encrypt each line and keep it's format so that So, I wrote the following program:
fileInputName = input("Enter the file you want to encrypt: ")
key = int(input("Enter your shift key: "))
outputFileName = input("Enter the file name to write to: ")
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
encryptedMessage = ""
for character in message:
letterIndex = message.split("\n")
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
print("The encrypted message is: {0}".format(encryptedMessage))
outputFile = open( outputFileName, "w")
print(encryptedMessage, file=outputFile)
outputFile.close()
print("Done writing encrypted message to file {0}".format(outputFileName))
I tried to use a split at \n, but the output is not formatted in three separate lines, instead it is all just one long string of encrypted letters.
Any ideas on how to split the encrypted message at the correct spot and have it display as such? I've tried multiple split methods and none have worked. Thank you so much.
As the other answers have said, you can replace
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
with
with open(fileInputName, "r") as f:
messages = f.readlines()
This way, messages will be a list of strings, where each string is the text from a single line in your input file. Then, with some slight modifications to your loop over each character in messages, you can encrypt each string from your messages list. Here, I replaced your encryptedMessage with currentEncryptedMessage and added encryptedMessages, a list that keeps track of the encrypted version of each string in messages.
encryptedMessages = []
currentEncryptedMessage = ""
for message in messages:
for character in message:
... # same as code provided
currentEncryptedMessage += encryptedCharacter
encryptedMessages.append(currentEncryptedMessage)
When writing to your file, you can iterate through each element in encryptedMessages to print line-by-line.
with open( outputFileName, "w") as outputFile:
for message in encryptedMessages:
print(message, file=outputFile)
And so your output text file will preserve the line breaks from your input file.
Instead of splitting at '\n', you can append all the characters in message that are not in alphabet to encryptedMessage when you encounter one.
for character in message:
if !(character in alphabet):
encryptedMessage += character
continue # this takes back to begin of the loop
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
Try changing:
message = fileInputOpen.read()
to
message = fileInputOpen.readlines()
This will make your file reads handle the file line by line. This will allow you to do your processing on a line by line basis first. Beyond that, If you want to encrypt each character, you'll need another for loop for the characters.
Instead of reading the file all at once. Read the lines individually.
f = open("file.txt")
for i in f.readlines():
print (i)
You'll have to loop each line and every character you want to
un-shift;
The script should only un-shift characters present in alphabet;
Checking for file existence is also a must or you may get errors if it doesn't exist.
with open... is the recommended way of reading and writing files in python.
Here's an approach:
import os
import string
fileInputName = input("Enter the file you want to encrypt: ")
while not os.path.exists(fileInputName):
fileInputName = input("{} file doesn't exist.\nEnter the file you want to encrypt : ".format(fileInputName))
key = int(input("Enter your shift key (> 0): "))
while key < 1 :
key = int(input("Invalid shift key value ({}) \nEnter your shift key (> 0): ".format(key)))
fileOutputName = input("Enter the file name to write to: ")
if os.path.exists(fileOutputName) :
ow = input("{} exists, overwrite? (y/n): ".format(fileOutputName))
if not ow.startswith("y"):
fileOutputName = input("Enter the file name to write to: ") # asks for output filename again
alphabet = string.ascii_letters + " "
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
with open(fileOutputName, "a") as outputFile: # opens out file
with open(fileInputName, "r") as inFile: # opens in file
for line in inFile.readlines(): # loop all lines in fileInput
encryptedCharacter = ""
for character in line: # loop all characters in line
if character in alphabet: # un-shift only if character is present in `alphabet`
letterIndex = alphabet.find(character)
encryptedCharacter += shiftedAlphabet[letterIndex]
else:
encryptedCharacter += character # add the original character un-shifted
outputFile.write("{}".format(encryptedCharacter)) # append line to outfile

How can i add the functions try/except in this code?

I'm still creating this code where via a dictionary attack i find a password, inserted by the user. However I would insert some controls in the input of the file's source (ex. when I type the source of a file that doesn't exist) and when I open a file but inside there isn't a word that match with the password typed by the user. My mind tell me that I can use istructions as "If, Else, Elif" but other programmers tell me that i could use the try except instructions.
This is the code:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print "\nThe password that you typed is : " + new_line + "\n"
except(
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)
You can put this as your "File does not exist" exception and after you open the existing file you can but an if statement to check if anything exist inside the file in your way:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
if os.stat( txt_file).st_size > 0: #check if file is empty
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print("\nThe password that you typed is : " + new_line + "\n")
else:
print "Empty file!"
except IOError:
print "Error: File not found!"
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)

Python syntax error while taking an IP address as an input

I have a text file called sample_ips.txt containing some random IP addresses as follows:-
182.0.0.15
182.0.0.16
182.0.0.17
I am giving an IP address as an input to check if that IP exist in the text file it prints true else false.
Here is my code snippet:-
ip_input = str(input("Enter IP:"))
ip = open("sample_ips", "r")
data = ip.readlines()
for ips in data:
ips = ips.strip("\n")
if ip_input in ips:
print "true"
else:
print "false"
It's throwing a syntax error
File "<string>", line 1
182.0.0.15
^
SyntaxError: invalid sytanx
I think it is not able to take the input as a string despite me declaring it as a string in my code. Any help?
Thanks
input_ip = raw_input("Enter IP:") # In python 2.x. If you use input() then type your inputs as string (>>Enter IP:"182.0.0.15")
#input_ip = input("Enter IP:") for python 3.x
with open("ip.txt", "r") as ip:
data = ip.readlines()
for ips in data:
ips = ips.strip("\n")
if input_ip in ips:
print ("true")
else:
print ("false")
Well, this works:
input = raw_input("Enter IP:")
ip = open("sample_ips.txt", "r")
data = ip.readlines()
for ips in data:
ips = ips.strip("\n")
if input in ips:
print "true"
else:
print "false"
:edit:
Python3 version
input = input("Enter IP:")
ip = open("sample_ips.txt", "r")
data = ip.readlines()
for ips in data:
ips = ips.strip("\n")
if input in ips:
print ("true")
else:
print ("false")

Categories

Resources