Script is skipping function - python

I have no idea whats going on with this code, for some reason it seems to just skip the function entirely.
try:
readHandle = open(fileName, 'r')
except IOError, ioe:
print "Cannot open file: ", fileName,"\n"
print "%s" %ioe
raise
lines = readHandle.readlines()
lineNum = 1
#read file line by line
for line in lines:
if line.startswith(':'):
#remove : from line
bits0 = line.partition(':')
#remove \n newlines
bits1 = bits0[2].partition('\n')
#split in to an array using , as delimiter
bits2 = bits1[0].split(',')
DrvrNum = bits2[0]
DrvrNam = bits2[1]
# Debug
if DBUG == 1:
print "DrvrNum and DrvrNam variable values"
print DrvrNum, DrvrNam
crcDrvr(DrvrNum, DrvrNam)
elif line.startswith('#'):
#Comment line
pass
elif line.startswith('Ss'):
#Crc line
pass
elif line.startswith('Zz'):
#end of file
pass
else:
print '\nError: line', lineNum , 'is an illegal entry'
print '\nPlease Check'
sys,exit(0)
lineNum = lineNum + 1
This is the function that is being skipped:
def crcDrvr(number,name):
convNum = int(number,16)
convNam = ''
for char in name:
hexChar = char.encode("hex")
print hexChar
can anyone tell me where I've gone wrong to cause my code to skip?
Sample data:
#DrvrDB
#
#
#
Ss1234
:744,Bob Hope
:747,Testy Tester
:777,Extra Guy
:0,dummy
Zz
#Driver#,DriverName
#end of file padding 1

I figured it out, some genius create the function crcDrvr twice with only a variable declaration so it must have been hitting that one
– Jim

Related

How to write Python Shell to an output text file?

I need to write my Python shell to an output text file. I have some of it written into an output text file but all I need is to now add the number of lines and numbers in each line to my output text file.
I have tried to add another for loop outside the for loop. I've tried putting it inside the for loop and it was just complicated.
Text file list of numbers:
1.0, 1.12, 1.123
1.0,1.12,1.123
1
Code:
import re
index = 0
comma_string = ', '
outfile = "output2.txt"
wp_string = " White Space Detected"
tab_string = " tab detected"
mc_string = " Missing carriage return"
ne_string = " No Error"
baconFile = open(outfile,"wt")
with open("Version2_file.txt", 'r') as f:
for line in f:
flag = 0
carrera = ""
index = index +1
print("Line {}: ".format(index))
baconFile.write("Line {}: ".format(index))
if " " in line: #checking for whitespace
carrera = carrera + wp_string + comma_string + carrera
flag = 1
a = 1
if "\t" in line: #checking for tabs return
carrera = carrera + tab_string + comma_string + carrera
flag = 1
if '\n' not in line:
carrera = carrera + mc_string + ne_string + carrera
flag = 1
if flag == 0: #checking if no error is true by setting flag equal to zero
carrera = ne_string
print('\t'.join(str(len(g)) for g in re.findall(r'\d+\.?(\d+)?', line )))
print (carrera)
baconFile.write('\t'.join(str(len(g)) for g in re.findall(r'\d+\.?(\d+)?', line ) ))
baconFile.write(carrera + "\n")
with open("Version2_file.txt", 'r') as f:
content = f.readlines()
print('Number of Lines: {}'.format(len(content)))
for i in range(len(content)):
print('Numbers in Line {}: {}'.format(i+1, len(content[i].split(','))))
baconFile.write('Number of lines: {}'.format(len(content)))
baconFile.write('Numbers in Line {}: {}'.format(i+1, len(content[i].split(','))))
baconFile.close()
Expected to write in output file:
Line 1: 1 2 3 Tab detected, whitespace detected
Line 2: 1 2 3 No error
Line 3: 1 Missing carriage return No error
Number of Lines: 3
Numbers in Line 1: 3
Numbers in Line 2: 3
Numbers in Line 3: 1
Actual from output file:
Line 1: 1 3 2White Space Detected, tab detected, White Space Detected,
Line 2: 1 3 2No Error
Line 3: 0Missing carriage returnNo Error
Number of lines: 3Numbers in Line 1: 3Number of lines: 3Numbers in Line 2: 3Numb
You have closed baconFile in the first open block, but do not open it again in the second open block. Additionally, you never write to baconFile in the second open block, which makes sense considering you've not opened it there, but then you can't expect to have written to it. It seems you simply forgot to add some write statements. Perhaps you confused write with print. Add those write statements in and you should be golden.
baconFile = open(outfile,"wt")
with open("Version2_file.txt", 'r') as f:
for line in f:
# ... line processing ...
baconFile.write(...) # line format info here
# baconFile.close() ## <-- move this
with open("Version2_file.txt", 'r') as f:
content = f.readlines()
baconFile.write(...) # number of lines info here
for i in range(len(content)):
baconFile.write(...) # numbers in each line info here
baconFile.close() # <-- over here
Here's a useful trick you can use to make print statements send their output to a specified file instead of the screen (i.e. stdout):
from contextlib import contextmanager
import os
import sys
#contextmanager
def redirect_stdout(target_file):
save_stdout = sys.stdout
sys.stdout = target_file
yield
sys.stdout = save_stdout
# Sample usage
with open('output2.txt', 'wt') as target_file:
with redirect_stdout(target_file):
print 'hello world'
print 'testing', (1, 2, 3)
print 'done' # Won't be redirected.
Contents of output2.txt file after running the above:
hello world
testing (1, 2, 3)

Why is my program not reading the first line of code in the referenced file(fileName)?

def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
infile=open(fileName , "r")
text=infile.readline()
count=0
while text != "":
text=str(count)
count+=1
text=infile.readline()
print(str(count)+ ": " + text)
infile.close()
main()
-the referenced .txt file has only two elements
44
33
-the output of this code should look like
1: 44
2: 33
-my output is
1: 33
2:
im not sure why the program is not picking up the first line in the referenced .txt file. The line numbers are correct however 33 should be second to 44.
The reason is explained in the comments:
def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
infile=open(fileName , "r")
text=infile.readline() ##Reading the first line here but not printing
count=0
while text != "":
text=str(count)
count+=1
text=infile.readline() ##Reading the 2nd line here
print(str(count)+ ": " + text) ##Printing the 2nd line here, missed the first
##line
infile.close()
main()
Modify the program as:
def main():
read()
def read():
fileName= input("Enter the file you want to count: ")
infile = open(fileName , "r")
text = infile.readline()
count = 1 # Set count to 1
while text != "":
print(str(count)+ ": " + str(text)) # Print 1st line here
count = count + 1 # Increment count to 2
text = infile.readline() # Read 2nd line
infile.close() # Close the file
main()
def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
with open(fileName,'r') as f:
print('\n'.join([' : '.join([str(i+1),v.rstrip()]) for i,v in enumerate(f.readlines())]))
main()
I'm very confused by your read function. You start by reading the first line into text:
text=infile.readline()
Presumable at this point text contains 44.
You then immediately demolish this value before you've done anything with it by overwriting it with:
text = str(count)
ie you read two lines before printing anything at all.
You should print the value of text before you overwrite it with the next readline.
Simply move the print statement before readline:
while text != "":
count+=1
print(str(count)+ ": " + text)
text=infile.readline()

Python string compare and replace

I have a .txt with:
#Date 111111:UhUidsiIds
#Name Sebastian-Forset
#Date 222222:UdfasdUDsa
#Name Sebastian_Forset2
#Date 333333:UDsafduD
#Name Solaris Mage
#Date 444444:Ghdsasra
#Name Marge S
and a file whith:
#Name Sebastian Forset
#Date 191020
#Name Sebastian Forset2
#Date 201020
#Date Homer S
#Date 281902
The names are the same, with some differences of characters (spaces, -, _ etc.)
I would copy the numbers of the second file to the first file in order to have a final file txt with:
#Name Sebastian Forset
#Date 191020:UhUidsiIds
#Name Sebastian Forset2
#Date 201020:UdfasdUDsa
#Name Solaris Mage
#Date 281902:UDsafduD
#Name Marge S
#Date 444444:Ghdsasra
This is my code, but merge the file, copy only same name
def isInFile(l, f):
with open(f, 'r') as f2:
for line in f2:
if l == line:
return True
return False
def similitudes(file1, file2):
same = 0
data = ''
copy = False
with open(file1, 'r') as f1:
for line in f1:
if copy == True:
data += line
if line == '\n' or line[0:6] != '#Name ':
copy = False
if (line[0:6] == '#Name ') or line[0:6] == '#Date ':
print line
if isInFile(line, file2) == True:
copy = True
data += line
print "true"
else:
print "ok"
same += 1
return data
def main(argv=2):
print (sys.argv[1])
print (sys.argv[2])
if argv == 2:
out = open('final.txt', 'w')
data = (
similitudes(sys.argv[1], sys.argv[2]) + '\n'
)
out.write(data)
out.close()
else:
print ("This program need 2 files")
exit (0)
return 0
if __name__ == '__main__':
status = main()
sys.exit(status)
First, list out the characters that will differ. Let's say "-" , "_" and " ".
Now split the two strings using these delimiters. you can use "re" package in python.
>>> a='Mr-Sebastian_Forset '
>>> import re
>>> re.split('- |_ | ',a)
['Mr', 'Sebastian', 'Forset']
If the resultant lists for the two strings are equal, paste the number in second file in first one.
You can use the same delimiter concept to split the number and paste it in other file.
Adding another answer, which will points out the bug in your code
Coming to the following piece of code
if (line[0:6] == '#Name ') or line[0:6] == '#Date ':
print line
if isInFile(line, file2) == True:
copy = True
data += line
Here, you are checking If your line starts with either "#Name " or "#Date ", and calling isInFile() method with line and file2 as arguments.
This is the first issue, there is no use of sending just one line that starts with "#Name " in your case.
If the current line starts with "#Date ", send the previous line and file as arguments to this method.
And second Issue is with the isInFile() definition, which is doing effectively nothing.
if l == line:
return true
You are just checking if two lines in file1 and file2 are same and if yes, you writing this line in sysout.
So, your program will just print the common lines between file1 and file2.
Modified code should like the below one:
def isInFile(l, f):
line_found = false
required_line = null
with open(f, 'r') as f2:
for line in f2:
if line_found:
required_line = line
break
elif l == line:
line_found = true
return (line_found, required_line)
def similitudes(file1, file2):
same = 0
data = ''
copy = False
previous_line = null
with open(file1, 'r') as f1:
for line in f1:
if copy == True:
data += line
if line == '\n' or line[0:6] != '#Name ':
copy = False
if (line[0:6] == '#Name '):
print line
previous_line = line
elif line[0:6] == '#Date ':
print line
file2_line_info = isInFile(previous_line, file2)
if file2_line_info[0] == True:
copy = True
data += file2_line_info[1]
print "true"
return data
def main(argv=2):
print (sys.argv[1])
print (sys.argv[2])
if argv == 2:
out = open('final.txt', 'w')
data = (
similitudes(sys.argv[1], sys.argv[2]) + '\n'
)
out.write(data)
out.close()
else:
print ("This program need 2 files")
exit (0)
return 0
if __name__ == '__main__':
status = main()
sys.exit(status)
Note: This is not the pythonic way of doing things. As I have mentioned in the above answer https://stackoverflow.com/a/34696778/3534696 use "re" module and solve the problem efficiently.
Read the first file into a dictionary, using maketrans/translate to clean up the name.
Using zip(file, file) to read 2 lines of the file at a time makes it much easier to handle.
And using .split(' ', 1)[1] to get rid of the first column.
And .strip() to get rid of any surrounding whitespace (i.e. \n)
Then you can read the second file updating the dictionary.
In Python3 this looks like:
>>> punc = str.maketrans('_-', ' ') # import string & string.maketrans() in Py2
>>> with open(filename1) as file1, open(filename2) as file2:
... data = {name.split(' ', 1)[1].strip().translate(punc):
... date.split(' ', 1)[1].strip().split(':')
... for name, date in zip(file1, file1)}
... for n, d in zip(file2, file2):
... data[n.split(' ', 1)[1].strip()][0] = d.split(' ', 1)[1].strip()
>>> data
{'Marge S': ['444444', 'Ghdsasra'],
'Sebastian Forset': ['191020', 'UhUidsiIds'],
'Sebastian Forset2': ['201020', 'UdfasdUDsa'],
'Solaris Mage': ['281902', 'UDsafduD']}
After that it is just a matter of writing the dictionary out to a new file.
>>> with open(<output>, 'w+') as output:
... for name, date in data.items():
... output.write('#Name {}\n'.format(name))
... output.write('#Date {}:{}\n'.format(*date))
Note: I had to change 'Homer S' to 'Solaris Mage' in the second file to get the stated output.

KeyboardInterrupt close failed in file object destructor: sys.excepthook is missing lost sys.stderr

#!/usr/bin/env python
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
f = open(filename, "r")
for line in f:
line = line.strip()
print line + "\n"
while line:
pos = find_position(line)
line2 = line[ : pos+1].split(" ")
length = len(line2)
last_word = line2[length -1]
try:
if re.search(r"[A-Z]+.*", last_word) or line[pos+1] != " " or line[pos+2].islower() :
print line[:pos+1],
line = line[pos+1:]
else:
print line[ : pos+1]
line = line[pos+1 :]
except :
print " error here!!"
f.close()
return " bye bye"
if __name__=="__main__":
print sentence_splitter(sys.argv[1])
on executing it
python sentence_splitter6.py README | more
error occur
KeyboardInterrupt
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
also i have to press clr+c
it is not closed by its own
tried stuffs on this
How to handle a file destructor throwing an exception?
How to silence "sys.excepthook is missing" error?
links also but not saisfied please help
First of all, your problem is here:
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
line is not modified, so if its true once, it's always true, the while have no way to end.
Then, the KeyboardInterrupt does not comes from your execution but from you pressing C-c, halting your program.
Also you should respect the PEP8 while writing python code, also you can check it with flakes8 and/or pylint.
Here is PEP8 compliant version (still have the infinite loop):
#!/usr/bin/env python3
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
with open(filename, "r") as infile:
for line in infile:
line = line.strip()
print(line + "\n")
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
if ((re.search(r"[A-Z]+.*", last_word) or
line[pos+1] != " " or
line[pos+2].islower())):
print(line[:pos+1], end='')
line = line[pos+1:]
else:
print(line[:pos + 1])
line = line[pos + 1:]
return " bye bye"
if __name__ == "__main__":
print(sentence_splitter(sys.argv[1]))
Finally, you should comment your code so everyone including you can understand what you're doing, like:
def find_position(line):
"""Finds the position of a pun in the line.
"""
Also find_pun_position is probably a better name...

Delete x-line paragraphs from text file with Python

I have a long text file with paragraph with 6 and 7 lines each. I need to take all seven line paragraphs and write them to a file and take six line paragraphs and write them to a file.
Or delete 6-line (7-line) paragraphs.
Each paragraph is separated with blank line (or two blank lines).
Text file example:
Firs Name Last Name
address1
Address2
Note 1
Note 2
Note3
Note 4
First Name LastName
add 1
add 2
Note2
Note3
Note4
etc...
I want to use python 3 for windows. Any help is welcome. Thanks!
As a welcome on stackoverflow, and because I think you have now searched more for a code , I propose you the following code.
It verifies that the paragraphs have not more than 7 lines and not less than 6 lines. It warns when such paragraphs exist in the source.
You'll remove all the prints to have a clean code, but with them you can follow the algorithm.
I think there is no bug in it, but don't take that as 100 % sure.
It isn't the only manner to do , but I choosed the way that can be used for all types of files, big or not: iterating one line at a time. Reading the entire file in one pass could be done, and then split into a list of lines, or treated with help of regexes; however , when a file is enormous, reading it all in one time is memory consuming.
with open('source.txt') as fsource,\
open('SIX.txt','w') as six, open('SEVEN.txt','w') as seven:
buf = []
cnt = 0
exceeding7paragraphs = 0
tinyparagraphs = 0
line = 'go'
while line:
line = fsource.readline()
cnt += 1
buf.append(line)
if len(buf)<6 and line.rstrip('\n\r')=='':
tinyparagraphs += 1
print cnt,repr(line),"this line of paragraph < 6 is void,"+\
"\nthe treatment of all this paragraph is skipped\n"+\
'\n# '+str(cnt)+' '+ repr(line)+" skipped line "
buf = []
while line and line.rstrip('\n\r')=='':
line = fsource.readline()
cnt += 1
if line=='':
print "line",cnt,"is '' , EOF -> the program will be stopped"
elif line.rstrip('\n\r')=='':
print '#',cnt,repr(line)
else:
buf.append(line)
print '!',cnt,repr(line),' put in void buf'
else:
print cnt,repr(line),' put in buf'
if len(buf)==6:
line = fsource.readline() # reading a potential seventh line of a paragraph
cnt += 1
if line.rstrip('\n\r'): # means the content of the seventh line isn't void
buf.append(line)
print cnt,repr(line),'seventh line put in buf'
line = fsource.readline()
cnt += 1
if line.rstrip('\n\r'): # means the content of the eighth line isn't void
exceeding7paragraphs += 1
print cnt,repr(line),"the eight line isn't void,"+\
"\nthe treatment of all this paragraph is skipped"+\
"\neighth line skipped"
buf = []
while line and line.rstrip('\n\r'):
line = fsource.readline()
cnt += 1
if line=='':
print "line",cnt,"is '' , EOF -> the program will be stopped"
elif line.rstrip('\n\r')=='':
print '\n#',cnt,repr(line)
else:
print str(cnt) + ' ' + repr(line)+' skipped line'
else:
if line=='':
print cnt,"line is '' , EOF -> the program will be stopped\n"
else: # line.rstrip('\n\r') is ''
print cnt,'eighth line is void',repr(line)
seven.write(''.join(buf) + '\n')
print buf,'\n',len(buf),'lines recorded in file SEVEN\n'
buf = []
else:
print cnt,repr(line),'seventh line: void'
six.write(''.join(buf) + '\n')
print buf,'\n',len(buf),'lines recorded in file SIX'
buf = []
if line=='':
print "line",cnt,"is '' , EOF -> the program will be stopped"
else:
print '\nthe line is',cnt, repr(line)
while line and line.rstrip('\n\r')=='':
line = fsource.readline()
cnt += 1
if line=='':
print "line",cnt,"is '' , EOF -> the program will be stopped"
elif line.rstrip('\n\r')=='':
print '#',cnt,repr(line)
else: # line.rstrip('\n\r') != ''
buf.append(line)
print '!',cnt,repr(line),' put in void buf'
if exceeding7paragraphs>0:
print '\nWARNING :'+\
'\nThere are '+str(exceeding7paragraphs)+' paragraphs whose number of lines exceeds 7.'
if tinyparagraphs>0:
print '\nWARNING :'+\
'\nThere are '+str(tinyparagraphs)+' paragraphs whose number of lines is less than 6.'
print '\n===================================================================='
print 'File SIX\n'
with open('SIX.txt') as six:
print six.read()
print '===================================================================='
print 'File SEVEN\n'
with open('SEVEN.txt') as seven:
print seven.read()
I also upvote your question because it is a problem not so easy that it's seems to solve, and to not let you with one post and one downvote, it is demoralizing as a beginning. Try to make your presentation better next time, as other said.
.
EDIT:
here's a simplified code for a text containing only paragraphs of 6 or 7 lines precisely, separated by 1 or 2 lines exactly, as stated in the problem's wording
with open('source2.txt') as fsource,\
open('SIX.txt','w') as six, open('SEVEN.txt','w') as seven:
buf = []
line = fsource.readline()
while not line: # to go to the first non empty line
line = fsource.readline()
while True:
buf.append(line) # this line is the first of a paragraph
print '\n- first line of a paragraph',repr(line)
for i in xrange(5):
buf.append(fsource.readline())
# at this point , 6 lines of a paragraph have been read
print '-- buf 6 : ',buf
line = fsource.readline()
print '--- line seventh',repr(line),id(line)
if line.rstrip('\r\n'):
buf.append(line)
seven.write(''.join(buf) + '\n')
buf = []
line = fsource.readline()
else:
six.write(''.join(buf) + '\n')
buf = []
# at this point, line is the empty line after a paragraph or EOF
print '---- line after',repr(line),id(line)
line = fsource.readline()
print '----- second line after',repr(line)
# at this point, line is an empty line after a paragraph or EOF
# or the first line of a new paragraph
if not line: # it is EOF
break
if not line.rstrip('\r\n'): # it is a second empty line
line = fsource.readline()
# now line is the first of a new paragraph
print '\n===================================================================='
print 'File SIX\n'
with open('SIX.txt') as six:
print six.read()
print '===================================================================='
print 'File SEVEN\n'
with open('SEVEN.txt') as seven:
print seven.read()

Categories

Resources