[Tutor] Copying one text file into another
Ed Connell
edwinconnell at gmail.com
Thu Aug 5 16:47:11 EDT 2021
Thanks for your suggestions. Though I can see why you thought of HOMEWORK,
that is funny since I will turn 80 in a few days. :)
I relaxed my "requirements" a bit (sorry), but I am interested in your
suggestions.
Recently I noticed that the same thing occurred in programs over and over -
like getting an integer in a certain range or confirming something - so I
developed some short functions to handle those situations. I am attaching
a printout that shows my code on the current topic as well as several of
those functions.
I am just having fun.
Thanks for all you do,
Ed Connell
Later I tried my hand at the rest and came up with the following. Again,
I'm just having fun!
Here the destination is a temp file as was suggested by someone.
def insert_file( dest, lookfor, filea, fileb ):
with open( dest, 'w' ) as fout:
with open( filea, 'r' ) as fin:
while True:
lin = fin.readline()
print( lin[:-1], file = fout )
if len( lin ) == 0:
print( '\n\n\n', file = fout )
return
if lookfor in lin:
break
with open( fileb, 'r' ) as fin2:
while True:
lin = fin2.readline()
print( lin[:-1], file = fout )
if len( lin ) == 0:
print( '\n\n\n', file = fout )
break
while True:
lin = fin.readline()
print( lin[:-1], file = fout )
if len( lin ) == 0:
print( '\n\n\n', file = fout )
return
if __name__ == '__main__':
insert_file( 'teds.py', 'XXXXX', 'eds.py', 'test.py' )
On Tue, Aug 3, 2021 at 1:55 PM Ed Connell <edwinconnell at gmail.com> wrote:
> Suppose you have two text files, A.txt and B.txt. You want to copy A into
> B at some designated place .Of course there is copy and paste, but I got
> interested in how you could do this with Python. Can you help?
>
> Ed Connell
>
> --
> I have a right and a left brain, but there is nothing right in the left
> one and there is nothing left in the right one!
>
>
--
I have a right and a left brain, but there is nothing right in the left one
and there is nothing left in the right one!
-------------- next part --------------
============================================================
# 8/5/21
print( 'One for the money...' )
def combine( destination, *source ):
with open( destination, 'w' ) as fout:
print( '\n\n\n\n============================================================\n\n\n', file = fout )
print( '\n\n\n\n============================================================\n\n\n' )
for src in source:
with open( src, 'r' ) as fin:
while True:
lin = fin.readline()
if len( lin ) == 0:
break
print( lin[ : -1 ], file = fout )
print( lin[ : -1 ] )
print( '\n\n\n\n============================================================\n\n\n', file = fout )
print( '\n\n\n\n============================================================\n\n\n' )
print( "That's all folks..." )
if __name__ == '__main__':
combine( 'tmp.txt', 'filework.py', 'binary_search.py', 'get_char.py', 'get_int_float.py',\
'int_pair.py', 'pick_from_list.py', 'yes_ok.py' )
============================================================
# 8/5/21
import random
probes = 1
thesize = 100
def binary_search( left, right, thelist, target ):
global probes # just used to see resulting operation
print( probes, ' ', end='' )
probes += 1
mid = ( left + right ) // 2
if right - left <= 3:
if right == len( thelist ):
right -= 1
for x in range( left, right ):
if thelist[ x ] == target:
print( 'Alternate: ', end='' )
return x
return -1
found = thelist[ mid ]
if found == target:
return mid
elif found < target:
left = mid + 1
elif found > target:
right = mid
return binary_search( left, right, thelist, target )
if __name__ == '__main__':
input( '\n\nFirst with integers. Press ENTER to start ...' )
right = thesize
thelist = sorted( [ random.randint( 0, 99 ) for _ in range( right ) ] )
print( '\n\n', thelist )
target = random.randint( 0, 99 )
print( '\n\ntarget: ', target, '\nprobes: ', end='' )
position = binary_search( 0, right, thelist, target )
if position >=0:
print( '\n\nposition: ', position )
start = position - 10 if position >= 10 else 0
print( '\n\n', thelist[ start : position ] )
print( '\n', thelist[ position ] )
print( '\n', thelist[ position+1: position+11 ] )
else:
print( '\n\nNot in the list...' )
input( '\n\nPress ENTER to continue to a list of floats...' )
probes = 1
right = thesize
thelist = sorted( [ round( random.random() * 10, 2 ) for _ in range( right ) ] )
print( '\n\n', thelist )
target = round( random.random() * 10, 2 )
print( '\n\ntarget: ', target, '\nprobes: ', end='' )
position = binary_search( 0, right, thelist, target )
if position >=0:
print( '\n\nposition: ', position )
start = position - 10 if position >= 10 else 0
print( '\n\n', thelist[ start : position ] )
print( '\n', thelist[ position ] )
print( '\n', thelist[ position+1: position+11 ] )
else:
print( '\n\nNot in the list...' )
============================================================
# 8/2/21
from msvcrt import getch
def getchar():
return chr( getch()[0] )
if __name__ == '__main__':
print( '\n\nPress some ', end = '' )
print( 'keys.\n\n q or Q to quit' ) # this works fine
while True:
k = getchar()
print( '+', k, 'ordinal =', ord(k), end = '' )
# it seems that if the end='' is followed by another call to getchar() there are problems
# try putting a # before the next statement ( the print() )
print( ' last' )
if k == 'q' or k == 'Q':
break
print( '\n\nTrying down ', end = '' )
print( 'here.\n' ) # again - works fine
============================================================
# 8/2/21
def getint( s, low = 0, high = None, show_range = False ):
low_limit = str(low) if low != None else '-inf'
high_limit = str(high) if high != None else 'inf'
if show_range:
s += ' ** range: ' + low_limit + ' thru ' + high_limit
while True:
result = input( s + ': ' )
if result == '':
return None
try:
result = int( result )
except:
print( 'Must be an integer...' )
continue
if (low != None) and (low > result ):
print( "Can't be less than ", low )
continue
if (high != None) and (high < result ):
print( "Can't be greater than ", high )
continue
return result
def getfloat( s, low = 0, high = None, show_range = False ):
low_limit = str(low) if low != None else '-inf'
high_limit = str(high) if high != None else 'inf'
if show_range:
s += ' ** range: ' + low_limit + ' thru ' + high_limit
while True:
result = input( s + ': ' )
if result == '':
return None
try:
result = float( result )
except:
print( 'Must be an float...' )
continue
if (low != None) and (low > result ):
print( "Can't be less than ", low )
continue
if (high != None) and (high < result ):
print( "Can't be greater than ", high )
continue
return result
if __name__ == '__main__':
a = getint( '\n\nEnter an integer', low = 9, high = 11, show_range = True )
print( 'Got ', a )
b = getint( '\n\nEnter a non-negative intger ' )
print( 'Got ', b )
c = getint( '\n\nEnter an integer less than zero ', low = None, high = -1 )
print( 'Got ', c )
a = getfloat( '\n\nEnter a number', low = 9, high = 11, show_range = True )
print( 'Got ', a )
b = getfloat( '\n\nEnter a non-negative number ' )
print( 'Got ', b )
c = getfloat( '\n\nEnter a number less than zero ', low = None, high = -1 )
print( 'Got ', c )
============================================================
# 8/3/21
def intpair( s, low=0, high=None ):
while True:
try:
a = input( s + ' Enter two integers separated by a period - (like: 15.7 or 9.34): ' )
if a == '':
return None, None
elif '.' not in a:
print( 'No period...' )
continue
a, b = a.split( '.' )
a, b = map( int, [ a, b ] )
if low != None and (a < low or b < low):
print( "Can't be less than ", low )
continue
if high != None and (a > high or b > high):
print( "Can't be greater than ", high )
continue
return a, b
except:
print( 'Invalid, must be two nonnegative integers seperated by a period ...' )
print( ' four examples: 6.8 : 34.21 : 12 . 23 : 0.15 ' )
print( ' four bad examples - not: 32 : 9-7 : 23.67.21 : 6.8 7' )
continue
if __name__ == '__main__':
x, y = intpair( s = '\n\nSomething - ' )
print( '\n\nx =', x, 'y =', y )
if x == '':
print( 'null str is True' )
============================================================
# 8/2/21
def getint( s: str, low = 0, high = None ):
while True:
try:
res = input( s )
if res == '':
return ''
res = int( res )
except:
print( 'Must be an integer...' )
continue
if (low != None) and (low > res):
print( "Can't be less than ", low )
continue
if (high != None) and (high < res):
print( "Can't be greater than ", high )
continue
return res
def pick_from_list( thelist: list ) -> str:
print()
thelist.sort()
newlist = [ 'None' ] + thelist
for i, nm in enumerate( newlist ): # None gets paired with 0
print( i, nm )
choice = getint( 'Choice? ', low = 0, high = len( newlist ) - 1 )
if choice == 0 or choice == '':
return None
else:
return newlist[ choice ]
if __name__ == '__main__':
mylist = [ 'top', 'bottom', 'side' ]
pick = pick_from_list( mylist )
print( pick, 'chosen' )
============================================================
# 8/2/21
def yes( s, default_yes = False ):
if default_yes:
s += ' (Y or y or null = yes): '
else:
s += ' (only Y or y for yes): '
result = input( s ).upper()
return True if result == 'Y' or (default_yes and result == '') else False
if __name__ == '__main__':
if yes( '\n\nDo something. ' ):
print( '\n\nTrue ' )
else:
print( '\n\nFalse ' )
if yes( '\n\nDo something. ', default_yes = True ):
print( '\n\nTrue ' )
else:
print( '\n\nFalse ' )
============================================================
More information about the Tutor
mailing list