Python: Finding and changing elements in fixed length records

3.7k Views Asked by At

I am very new to programming, and have hit a wall with file handling this week. I have the following prompt:

Fixed Length Records

You will be passed the filename P, firstname F, lastname L, and a new birthday B.

Load the fixed length record file in P, search for F,L in the first and change birthday to B.

Then save the file.

The inputs are provided:

import sys
P= sys.argv[1] 
F= sys.argv[2]
L= sys.argv[3]
B= sys.argv[4]

My Code:

file1 = open(P, 'r')

data = file1.read()


for i in range(0, len(data)):
  if F and L not in data: 
    data.append(i)
  if F and L in data: 
    data.replace(B,B)


file1 = open(P, 'w')
file1.write(data)
file1.close()

This is obviously not working, but I am spinning wheels. I need to figure out how to change B, but can't quite get there. This is the output:

Program Output

Your program output did not match the expected output.

Your output:

Adam Smith 11111985Theodore Anderson
03201990Monty Biscuit-Barrel 10181980Adam Smithers
10101960Ruthy Anderson 06062010

Expected output:

Adam Smith 11111985Theodore Anderson
03201990Monty Biscuit-Barrel 10181980Adam Smithers
00000000Ruthy Anderson 06062010

I can't figure out how to change the birthday to B.

3

There are 3 best solutions below

0
On

This line seems to be one problem: data.replace(B,B) What does it mean to replace B with B?

Also, what is data.append(i) doing? You are adding an integer at the end of the data you read? I don't understand.

I would like to help out but I don't understand what you are doing. If you have posted the code somewhere online and comfortable sharing it, send a link to it. Also as I requested, you need to share with us the file that you are reading, and some sample data that is being passed in, so we can see whats happening.

0
On

It would help if we could see the arguments being passed to the program.
Also, in your loop, when you are testing for:
if F and L not in data
You're actually saying:
if F != None and L not in data
Try this instead:
if F not in data and L not in data

0
On

Here is how I did it in the Codio challenge and it did pass the check

import re #import regular expressions. Put under the "import sys"

file1 = open(P, 'r') 
data = file1.read() 
file1.close() 


found = re.findall(F + ' *' + L + ' *', data) 
chars = len(found[0])

beginChar = data.find(found[0])
birthday = data[beginChar + chars:beginChar + chars + 8]
data = data.replace(birthday, B)

file1 = open(P, 'w')
file1.write(data)

file1.close 

Hope this helps out!