Ask coding questions

← Back to all posts
How do I change certain characters within a file using user input and loops?
TheFlooBearer (7)
I need to find a way to change the characters in the file that are integers into the variable that is inputted. Then, I need to have the program re-loop so that the user can re-change the variable as needed.

mwilki7 (1078)

I'm getting a 404 (page not found) error. Do you have the correct link or is your repl public?

As for the description of the problem,
You want to know how to (for example) change:


to different numbers, line by line then reloop if necessary?

TheFlooBearer (7)

@mwilki7 Yes, that description fits perfectly

mwilki7 (1078)

@TheFlooBearer sorry for the late reply but here is a sample snippet

2  filename = 'test.txt'                        # edit filename here
3  outputfile = filename                        # output overwrites original file
5  lines = open(filename).read().splitlines()   # put all lines in file into an 6  array
7  for i in range(len(lines)):                  # loop through the array
8      if lines[i] == "3":                      # if current line has a 3
9          lines[i] = "9999"                    # replace it with 9999
11 open(outputfile,'w').write('\n'.join(lines)) # write output

If you want to reloop, then wrap lines 4 thru 11 into a while loop (or for loop)

TheFlooBearer (7)

@mwilki7 That makes sense. Even after a lot of research, I never found the [splitlines] function, so, that's great. I see what's happening and what it's doing. Thank you!

mwilki7 (1078)

@TheFlooBearer I'm surprised there is no easy to find solution for this on python. This took a lot of googling and I found a lot of confusing answers.

TheFlooBearer (7)

@mwilki7 Yeah. I tried stack Overflow, and... Didn't understand much of what I saw