Ask coding questions

← Back to all posts
1
How do I change certain characters within a file using user input and loops?
TheFlooBearer (2)

https://repl.it/@TheFlooBearer/While-loop-Character-specifics
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.

Commentshotnewtop
1
mwilki7 (117)

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:

file.txt
1
285
45
62
8
19
56
2
...

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

1
TheFlooBearer (2)

@mwilki7 Yes, that description fits perfectly

1
mwilki7 (117)

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

1  
2  filename = 'test.txt'                        # edit filename here
3  outputfile = filename                        # output overwrites original file
4  
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
10 
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)

1
TheFlooBearer (2)

@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!

1
mwilki7 (117)

@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.

1
TheFlooBearer (2)

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