#πŸ”’ how do i replace a character in a file OR in a string?

162 messages Β· Page 1 of 1 (latest)

limpid wraith
#

lets say i have a file, and it says "hello". how would i replace a certain index's value

example: file[3] = b >>> "helbo"

or if thats not possible, im happy with doing the same to a string

fallow dockBOT
#

@limpid wraith

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

limpid wraith
#

due to the nature of the request, i can also pretty much exclusively use 1 variable but if i have to use another then i suppose i can explain that one

rocky galleon
#

You basically have to do it by reading the entire file, changing what you want, then writing the entire contents back to the file

#

You could open the file with 'a' mode, then seek to where you want to modify in the file, then .write() what you want. But this will always overwrite the number of bytes at that location (as in, it won't insert)

limpid wraith
#
cache = open("CPU/" + register + ".txt", "r")
cache = [cache.read(), cache.close()][0]
cache = open(cache,"w")
## something cool
cache.close()

this is what i have so far lmao

limpid wraith
#

idk why theres an indent there, ignore that

rocky galleon
#

Yeah i think you were trying to do what i suggested but didn't quite get there

limpid wraith
#

seems about right

#

i just need to change a digit

#

00000000 to 00000010 for example

rocky galleon
#
with open('whatever.txt', 'r') as cache:
  contents = cache.read()

# modify contents
contents[3:5] = 'HI'

#write back to file
with open('whatever.txt', 'w') as cache:
  cache.write(contents)
limpid wraith
#

alright hold on let me try to implement + understand this

rocky galleon
#

the with and open is basically a shorthand for doing something like

try:
  cache = open('whatever.txt', 'r')
  contents = cache.read()
finally:
  cache.close()
limpid wraith
#

remember, one variable that is not a parameter. im trying to figure out if this meets this requirement

#

becasue this is a function

limpid wraith
rocky galleon
limpid wraith
#

i dont fully get the with open as thing on reflection...

#

so it just makes something true until its over then makes it false?

rocky galleon
#

If you want to dig into it, this is called a "context manager"

#

so the file open() implements this interface

#

but yeah, when the context manager is done, it implicitly ensures that the file obj gets .close()'d even if there's an exception somewhere

limpid wraith
#

without close even being said

#

thats cool

#

i really like that

#

probably should've used that before

rocky galleon
#

Now you know πŸ™‚

limpid wraith
#

i will now implement this and see what happens

limpid wraith
#

see that was what i thought happened but yk

ivory briar
ivory briar
#

no reading required

limpid wraith
#

so do i just google how to use the append and be done with it?

#

actually i have no idea how to word that

ivory briar
#

... the append?

limpid wraith
#

a = append

#

because its adding to a file

#

but i dont know how to do it at an index

ivory briar
#

ah, 'a' doesn't work, it cannot seek into the middle of a file, you need 'r+' mode

#

it does makes sense since 'a' means 'append', as in adding to the end of the file...

limpid wraith
#

what is even that

#

can i just write , "r+"

#

surely not

ivory briar
#

so:

  • open file in 'r+' mode (reading and writing mode)
  • seek to the index you want
  • write
ivory briar
limpid wraith
#

oh

#

my

#

good lord

ivory briar
#

why they didn't call it 'rw' i'll never know

limpid wraith
#

THATS A THING?

#

IM QUAKING THAT SAVES SO MUCH TIME

ivory briar
limpid wraith
#

i woulda thought that would return the value at that index

ivory briar
#

it doesn't really return anything useful, it changes the file pointer so that subsequent reads and writes are done at that location

limpid wraith
#

ok let me try to cook with this and ill let you know if i do it wrong

ivory briar
#

if you must know, it returns the index you sought to, this is usually equal to the input index but may be lower if the file is too short

limpid wraith
#
cache = "CPU/" + register + ".txt"
cache = open(cache,"r+")
cache.seek(index)
cache.write(x)

like this..?

ivory briar
#

yes, use context managers though

also i don't like using the same variable name for two different things

limpid wraith
#

i agree, but thats part of the task i have been given

#

im allowed one non-parameter internal variable

limpid wraith
#

it results in extreme agony

rocky galleon
#

wow

ivory briar
#

if you're restrained by the task in this way then i assume you're probably not allowed to use context managers either

rocky galleon
#

What are your requirements?

limpid wraith
#

one internal variable that isnt a parameter, all other variables must be written to a file

#

this is the setup so far

#

named after intel 64 bit registers, except dvd which is non volatile

rocky galleon
limpid wraith
#

all memory is cleared after the program finishes, and is created when the program starts

limpid wraith
#

its not a formal task, im way ahead in computer science so my teacher has intentionally given me a, and i quote, "BS task"

#

so far it can run applications and navigate through directories

rocky galleon
#

What does this particular function do then that you're working on?

limpid wraith
#

it helps in me writing applications

#

im writing a snake game in it and i need to change the map (which is stored in one variable)

#

its stored as about 40 dashes, and i need to change one of the dashes to be the head of the snake based on the snake head's coordinates

#

sort of like this

limpid wraith
#

i did something wrong and i dont know what

ivory briar
# limpid wraith hey wait no

don't use strings as indices```py

f = open(r'C:\Users\nesfi\Desktop\record.sma', 'r+')
f.seek("123")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
f.seek(123)
123```

#

it's a very unhelpful error message, that's for sure

limpid wraith
#

is it a string

#

i didnt know that

#

hold on

#

ill just add int() into the mix and see if that resolves it

limpid wraith
#

WHAT DO YOU MEAN "INVALID ARGUMENT" I GAVE YOU AN INTEGER YOU PICKY-

ivory briar
#

if it's an integer then it's probably negative```py

f = open(r'C:\Users\nesfi\Desktop\record.sma', 'rb+')
f.seek(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument```at this point it's probably more your fault

#

!e i recommend printing values that you're unsure of, printing the unambiguous representation is doubly useful:

s = "123"
i = 123
print(s)
print(i)
print(repr(s))
print(repr(i))```
fallow dockBOT
limpid wraith
#

thats how code works

#

i would really doubt you can read this, but i dont see how this is a negative

#

the red lines are the ones that matter lmao

#

oh hold on

#

i see it now

#

i see the light, i forgot the [1]

#

also a lot of ints

ivory briar
#

the error messages from f.seek aren't that terrible but they could be way better

limpid wraith
#

except the one time when it was python's fault but thats a different story

#

the error messages, however, will always be python's fault

#

i will never forget the one time when it was actually python's fault

ivory briar
#

python does have its share of design flaws, for example the flawed implementation of r-strings making r"\" a syntax error

limpid wraith
#

r-strings?

ivory briar
#

why don't they just make \ properly "raw" like the r-prefix suggests, so it doesn't expect any sequence after it...

yes, r-strings, they're for when you're too lazy to double the backslashes to escape their special meaning:
"C:\\Users\\me\\Desktop"
is equivalent to
r"C:\Users\me\Desktop"

unfortunately they still retain special meaning, for no apparent reason, at the end of the string:
r"C:\Users\me\Desktop\" # Syntax error!

limpid wraith
#

ah

#

weird

#

also it seems ive gone up a layer to a point where code that works is no longer working and im even more confused

#

unless the thing at the bottom IS the whole error

ivory briar
#

... you're using exec? why?

#

that is almost certainly unneeded

limpid wraith
ivory briar
#

why? what is being run?

rocky galleon
#

that's...dangerous

#

but yeah why not just import them?

limpid wraith
#

im writing the programs

limpid wraith
ivory briar
limpid wraith
#

also, using import anywhere other than the top of the code is a weird idea, and would be unnecessary

ivory briar
#

there's .py code in them, they may as well be

limpid wraith
#

python syntax though, yeah

#

but then what

ivory briar
limpid wraith
#

you import it, and run it?

#

why not just exec

limpid wraith
ivory briar
#

you import it and access the attributes you're interested in

limpid wraith
#

line by line, indiscriminately

#

the user chooses an app, they could design it themself and have it on a usb stick for all i care

#

also, they might run an apo twice, then importing twice is weird

ivory briar
#

there's a multitude of reasons for why exec is not a good idea

the most pertinent: it easily leads to errors that are very hard to debug, unmaintainability

limpid wraith
#

but i dont wanna import within a match case, WITHIN a loop

#

that sounds bad

ivory briar
#

it's for executing user programs in your OS thing, right?

limpid wraith
#

pseudo-OS, yeah

#

im not THAT epic

limpid wraith
ivory briar
#

executing such code directly gives full uncensored access to the pseudo-OS, all global state, the user will be walking on eggshells at constant risk of overwriting a random name they weren't supposed to and bricking your code

the way drop-in script modules are usually made in python is that they adhere to some API; code is located within functions that are called at specific times, for example a function called init could in one such API be called as soon as the module is loaded, or a function called think is called every time something is updated, etc

limpid wraith
#

i fully accept that for a real OS, this would be a terrible idea

ivory briar
#

overwriting crucial registers is less of a problem imo, besides the registers could just be exposed in their entirety by the API, random variable collisions with the main script is the primary concern

#

blindly combining two scopes is massively annoying, imports fix that and there isn't really any reason to avoid it other than you think it's "weird"

limpid wraith
#

the goal is to let them break it if they want, and i think exec works for that idea

limpid wraith
ivory briar
#

imports fix blindly combining two scopes, reducing cognitive load (which variable names are off-limits?) when making user scripts and ensuring that they won't randomly break if you add a new variable in the OS (future-proofing)

by throwing user scripts into the middle of your code, they're made this much more fragile; any change on the OS level (small implementation changes, adding an unrelated variable or two) could affect them, rather than any change on the API level - they're hard to consider user scripts at this point, when they're getting included directly in the OS source code

even for a small fun project i wouldn't contemplate using exec for this, but i understand that avoiding dynamic drop-in imports means there is less complexity, depth, in the OS implementation, this is naturally very desirable if you're not quite ready to dive into dynamic module loading, it just hurts to look at because you're shouldering a burden that is completely avoidable

limpid wraith
# ivory briar imports fix blindly combining two scopes, reducing cognitive load (which variabl...

i can see how import is a lot better in 99/100 cases, but the things youre describing are intentional, as i want every program to work with the same environment.

example: it says in the developer guide not to use any internal variables except maybe cache in very rare occasions. despite the fact that internal variables work. this means that different applications can work together in weird ways, which are destroyed by just using regular variables

#

like how i can make a program that just figures out what the last program did, even though thatd be hard, itd be next to impossible without a set of intentionally exploitable rules

#

the rules exist to make exploitation and hacking easier, not harder

fallow dockBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.