#π how do i replace a character in a file OR in a string?
162 messages Β· Page 1 of 1 (latest)
@limpid wraith
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.
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
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)
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
it doesnt need to insert, it needs to overwrite
idk why theres an indent there, ignore that
Yeah i think you were trying to do what i suggested but didn't quite get there
seems about right
i just need to change a digit
00000000 to 00000010 for example
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)
alright hold on let me try to implement + understand this
the with and open is basically a shorthand for doing something like
try:
cache = open('whatever.txt', 'r')
contents = cache.read()
finally:
cache.close()
remember, one variable that is not a parameter. im trying to figure out if this meets this requirement
becasue this is a function
alright thats very helpful as a resource
Sure. It's best practice for using file handles
i dont fully get the with open as thing on reflection...
so it just makes something true until its over then makes it false?
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
without close even being said
thats cool
i really like that
probably should've used that before
Now you know π
i will now implement this and see what happens
hey wait just one second
see that was what i thought happened but yk
this would require throwing the contents into a bytearray, since strings/bytes can't be mutated
if you're sure you really only want to open a file, overwrite a byte at a particular index, then done, then the simplest option is this
no reading required
so do i just google how to use the append and be done with it?
actually i have no idea how to word that
... the append?
a = append
because its adding to a file
but i dont know how to do it at an index
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...
so:
- open file in 'r+' mode (reading and writing mode)
- seek to the index you want
- write
that's what it's called
why they didn't call it 'rw' i'll never know
how do i do step 2 tho
f.seek(index)
and, what exactly does that return? how can i use something like that to change a value
i woulda thought that would return the value at that index
it doesn't really return anything useful, it changes the file pointer so that subsequent reads and writes are done at that location
ok let me try to cook with this and ill let you know if i do it wrong
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
cache = "CPU/" + register + ".txt"
cache = open(cache,"r+")
cache.seek(index)
cache.write(x)
like this..?
yes, use context managers though
also i don't like using the same variable name for two different things
i agree, but thats part of the task i have been given
im allowed one non-parameter internal variable
Oh woops
it results in extreme agony
wow
if you're restrained by the task in this way then i assume you're probably not allowed to use context managers either
What are your requirements?
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
I mea what are you supposed to do? What's the entire task?
all memory is cleared after the program finishes, and is created when the program starts
make pseudo-OS
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
What does this particular function do then that you're working on?
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
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
is it a string
i didnt know that
hold on
ill just add int() into the mix and see if that resolves it
i have elected that python errors are not helpful in this particular field
WHAT DO YOU MEAN "INVALID ARGUMENT" I GAVE YOU AN INTEGER YOU PICKY-
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))```
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 123
002 | 123
003 | '123'
004 | 123
it is entirely my fault
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
true, the machine just does what you tell it to, but human blunders lead to human confusion
the most egregious example i can imagine is this php error that's inexplicably in hebrew instead of english:
https://stackoverflow.com/questions/592322/php-expects-t-paamayim-nekudotayim
the error messages from f.seek aren't that terrible but they could be way better
i, at no point, would say the code errors are python's fault
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
python does have its share of design flaws, for example the flawed implementation of r-strings making r"\" a syntax error
r-strings?
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!
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
its reading external files, and running the contents
why? what is being run?
my apps
if you have more code in separate .py scripts, then meltz is right, import them
also, using import anywhere other than the top of the code is a weird idea, and would be unnecessary
they arent .py
there's .py code in them, they may as well be
exec is a much weirder idea, it's a giant red flag anywhere it's used
its my code, i wrote it
you import it and access the attributes you're interested in
i just want to run the code it contains
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
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
it's for executing user programs in your OS thing, right?
but yes. essentially
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
correct.
if i was attempting to write stable code for actual home use, i would be doing that. however, my goal is to give 100% freedom to the user, including the ability to brick the OS by rewriting crucial registers.
it says within the developers guide which registers should be left alone, but if they still want to use them then they can.
i fully accept that for a real OS, this would be a terrible idea
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"
yeah the one variable (cache) is mentioned. basically says don't use cache unless you have a very specific need and know what you're doing or want to break something
the goal is to let them break it if they want, and i think exec works for that idea
wdym by imports "fix" that.
i want it to behave as if their code was thrown directly into the middle of my code
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
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
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.