Python program to match string based on user input - python

I need to write a python program that allows user to enter input
like Apple,Ball and it if matches the line in the file print it.
so far I am able to get this.
import re
import sys
print('Enter the values')
value1=input()
try:
filenm1="D:\names.txt"
t=open(filenm1,'r')
regexp=re.search(value1,line)
for line in t:
if regexp:
print(line)
catch IOerror:
print('File not opened')
sys.exit(0)
Sample Input File
Apple
Ball
Stackoverflow
Call
Doll
User input : App
Output : Apple
now I want to modify this program to search by
user input : App,Doll
Output :
Apple
Doll

You can change your loop into this:
import sys
print('Enter the values')
value1=input()
value1=value1.split(',')
try:
filenm1="D:\names.txt"
t=open(filenm1,'r')
for line in t:
alreadyPrinted = False
for value in value1:
if value in line:
if not alreadyPrinted: #this bit prevents line being printed twice
print(line)
alreadyPrinted = True
except IOerror:
print('File not opened')
sys.exit(0)

Related

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.

Read an input file in python

I have an input file which looks like
===========================
__A= 2.3
__b= 3.26
===========================
__ctx= 4.2
===========================
__itermax= 100
__errmax= 1e-07
Using this inputfile a collection of outputs within a different code( not implemented in python) has been generated. I am now trying to write some Python scripts to read this input file as well as other generated outputs to perform postproccessing analysis.
I thus would like to extract the value of each parameter(A, b, ctx, ...) by a python script. Please note that this input file is distinct from the setting file discussed here as I can not perform any modification on the structure of the input file.
I have tried
import sys
try:
directory_name=sys.argv[1]
print(directory_name)
except:
print('Please pass directory_name')
input_file = directory_name +"input.txt"
with open(input_file) as fin:
for line in fin:
exec(line)
The error that I am encountering after running the code is
File "code.py", line 14, in <module>
exec(line)
File "<string>", line 1
===========================
^
SyntaxError: invalid syntax
Any suggestion on improving this code, or with a different outputting method (e.g. as a dictionary), to obtain the values of the parameters is helpful.
Do you wanna exec the string "==================" ?
This string is not a python code.
There is a lazy way, use try ... except ... to resolve this.
import sys
try:
directory_name=sys.argv[1]
print(directory_name)
except:
print('Please pass directory_name')
input_file = directory_name +"input.txt"
with open(input_file) as fin:
for line in fin:
try:
exec(line)
except Exception as e:
print(e)
Another way is you can remove all unuseful strings before you exec them.
Try a simple regular expression:
import re
e = r'^__(.*?)=(.*?)$'
with open('data.txt') as f:
print(dict(re.findall(e, f.read(), re.M)))
This will print:
{'A': ' 2.3', 'b': ' 3.26', 'ctx': ' 4.2', 'itermax': ' 100', 'errmax': ' 1e-07'}
Executing random lines of code from a file is risky, and a bit 'hacky'. If you really want to do it, the easiest way to fix your code is to just try each line:
import sys
try:
directory_name=sys.argv[1]
print(directory_name)
except:
print('Please pass directory_name')
input_file = directory_name +"input.txt"
with open(input_file) as fin:
for line in fin:
try:
exec(line)
except:
print("Line invalid: {}".format(line))
for extract thei value use re.search
import re
import sys
textfile = sys.argv[1]
f = open(textfile, 'r').readlines()
for l in f:
extract = l.rstrip()
try:
f = re.search('__A= (.*)', extract)
return True
except:
return False
valueA = f.group(1)
print valueA
you first have to check "line" makes sens to be executed.
the problem is when line = "========="
you can use :
if line.startwith("===")
continue
to skip it.
or
if line.startwith("__"):
exec(line)
to avoid exectuting unknown stuff

Python script error- Save output to a text file

I am trying to save the output to a file and the indentations are ok.. but I keep getting this error please see below:
This is the error below:
Traceback (most recent call last):
File "command.py", line 36, in <module>
file.write(output)
TypeError: expected a character buffer object
Can someone look at my code below and see what I am doing wrong. I am new to python so any help would be appreciated.
#Importing the necessary module. help
from trigger.cmds import Commando
#Asking the user for input.
devices = raw_input('\nEnter devices separated by comma: ')
commands = raw_input('\nEnter commands separated by comma: ')
#Splitting the devices/commands entered by the user.
devices_list = devices.split(',')
commands_list = commands.split(',')
#Running all given commands on all given devices.
cmd = Commando(devices = devices_list, commands = commands_list)
#Executing all the work.
cmd.run()
#Capturing the results
output = cmd.results
#print output
#Asking the user if they want to print to screen or save to file.
user_option = raw_input('Type "p" to print to screen or "s" to save to file: ')
if user_option == 'p':
print output
elif user_option == "s":
filename = raw_input('Please name your file. Example: /home/ubuntu/bgp.txt: ')
#Print the output to file.
with open(filename, 'w') as file:
file.write(output)
print "Done...Check out %s to see the results." % filename
#End of Program
Please help with this code
Convert output variable to string object using str method
EX:
with open(filename, 'w') as file:
file.write(str(output))

Append not saving for external file in python

I'm trying to figure out how to make sure that when I run a new dict entry that it actually saves. Before last exception, when you "print(dictio.fullDict3[firstLetter])", it shows the new appended dict entry, but doesn't actually save in the external file called dictio.
The following is the main:
import fileinput
import dictio
from dictio import fullDict3
while True:
try:
srcTxt = input("Input word you want to look up: ")
firstLetter = srcTxt[0]
print(dictio.fullDict3[firstLetter][srcTxt])
except:
try:
queryInput = input('What does '+srcTxt+' mean?: ')
with open("C:\\Users...\\dictio.py", "a"):
dictio.fullDict3[firstLetter].update({srcTxt:queryInput})
print(dictio.fullDict3[firstLetter])
except:
print("error has occured.")
The following is the external file called dictio.py that holds the dictionary:
fullDict3 = {
'0':{
'0data':'0datttaaa',
'0mada':'0mmmaadaa'
},
'a':{
'arbre':'tree',
'arc-en-ciel':'rainbow'
},
'b':{
'bierre':'beer',
'belle':'beautiful'
}
}
You can't change the contents of a module by operating on the module's contents via import. There is no reason to import fullDict3. Instead, store your starting structure in fullDict3.json. Convert that file to a Python object via json.load -- that returns a dict you can change. When you have the updated dict ready to write to disk, save it via json.dump.
Alright. Haven't had much time to code, but finally fixed my issue after some reading and trial an error, for anyone that comes across this for answers, however, there could easily be a cleaner and more efficient way to get it done:
while True:
try:
srcTxt = input("Input word you want to look up: ")
firstLetter = srcTxt[0]
if srcTxt == "ESC":
break
print(dictio.fullDict3[firstLetter][srcTxt])
except:
try:
queryInput = input('What does '+srcTxt+' mean?: ')
with open('C:\\Users...\\dictio.py', 'r') as f:
fullDict3[firstLetter].update({srcTxt:queryInput})
newDict = "fullDict3 = "+json.dumps(fullDict3)
with open('C:\\Users...\\dictio.py', 'w') as f:
f.write(newDict)
f.close()
except:
print("error has occured.")

prevent the closure of command Prompt with Python when an "exception" occurs

I have a script in Python 2.7 converted in executable with py2exe. The INPUT data is a text file where the delimiter need to be valid following this function:
# Check if delimeter is valid
def get_parse(filename, delimiters=['\t', ',', ' ', ':', ';', '-']):
with open(filename) as f:
f.next()
secondline = f.next()
for delimiter in delimiters:
if len(secondline.rstrip().split(delimiter)) >= 3:
return delimiter
raise Exception("couldn't find a delimiter that worked!")
When the delimiter is not valid (ex: a dot) i am looking for two solution in a Python elegant way:
Until the right INPUT data is not load you can not pass to OUTFILE
or
The script break the code, show the error, but the windows (when is a
*.exe) doesn't close immediately leaving the user without an explanation
INPUT = raw_input("Input (*.txt): ")
while not os.path.exists(INPUT):
print IOError("No such file or directory: %s" % INPUT)
INPUT = raw_input("Input (*.txt): ")
try:
parse = get_parse(INPUT)
except Exception:
print ValueError("Delimiter type not valid")
break
OUTPUT = raw_input("Output (*.txt): ")
with this solution (break) the Window of my *.exe file close leaving the user without an explanation
You are not really searching for a delimiter, just a character in a string. You should really use the CSV module for this.
from __future__ import print_function
delimiters=['\t', ',', ' ', ':', ';', '-']
def getfile():
fname =""
while fname is "":
fname = str.lower(raw_input("Input(*.txt): "))
while fname.endswith(".txt") is not True:
print ("File must be .txt")
fname = str.lower(raw_input("Input(*.txt): "))
if fname.endswith(".txt"):
try:
with open(fname,'rb') as f:
parsed = False
while not parsed:
data = f.readline()
for d in delimiters:
if d in data:
print ("Delimiter: {0} found".format(d))
parsed = True
# do your additional stuff here
else:
print ("Unable to find delimiter {0}".format(d))
parsed = True
except IOError as e:
print( "Error: ", e)
getfile()
You can hook the exception handler for uncaught exceptions using sys.excepthook, and have it call raw_input() (or input() in 3.x) as per this answer.
For a quick example:
import sys
def wait_on_uncaught_exception(type, value, traceback):
print 'My Error Information'
print 'Type:', type
print 'Value:', value
print 'Traceback:', traceback
raw_input("Press any key to exit...")
sys.excepthook=wait_on_uncaught_exception
Just modify that to have whatever output or whatever you want (I suggest looking into the traceback module).
But if you want it more specific to your code, then just put raw_input("Press any key to exit...") in the solution you already have, and it should be fine. The above should provide a more general solution.

Categories