Home > front end >  What's the Python's file logic when reading vs writing or appending?
What's the Python's file logic when reading vs writing or appending?

Time:10-03

Probably a dumb question here, but it's my curiosity.

I firstly thought that when using "a", the method .append() is automatically incorporated in it which makes sense since adding "a" should already indicate to the program our final goal, but i don't really understand why it's not the case when using "r" and, instead, we have to add also .read() at the end of the line.

Here is an example:

file1 = open("test.txt", "a")    #no .append() or something needed here
file1.write("Hello")
file1.close()

var_lecture = open("test.txt", "r").read()    #.read() necessary
print(var_lecture)

Can someone give me a better understanding of this?

CodePudding user response:

The option is changing the the way the method 'write' is writing into the file. If you use the option 'w' it will overwrite the whole file. If you are using 'a' it will append the text to the text, that is already in the file

def read_test():
    content = open("test.txt", "r").read()
    print(content)

def write_test():
    file = open("test.txt", "w")
    file.write("test")
    file.close()

def append_test():
    file = open("test.txt", "a")
    file.write("test")
    file.close()

write_test()
read_test()
# output: test
write_test()
read_test()
# output: test
append_test()
read_test()
# output: testtest

CodePudding user response:

when you use mode append this mean the pointer editor After the last letter on the page for example

text.txt  contain "my name is name"
f=open("text.txt",mode="a",encoding="utf-8")
f.write("  ggg  ")
f.close()
#result "my name is name  ggg  "

when you read you read letters from pointer position to last letter for example text.txt contain "my name is name"

  f=open("text.txt",mode="a ",encoding="utf-8")
    print(f.read()) 
    f.seek(5) # to set it in poition 5
    print(f.read())
    f.close()  
#""      # so when you read it  is empty
#me is name

at the write mode you will create a new file and write from position 0 if the file not exist , if exist the truncate function will be use that mean all letters after pointer(at position 0) will be deleted

if you want to append at specific positions for example text.txt contain "my name is name"

f=open("text.txt",mode="r ",encoding="utf-8")
f.seek(7)
f.write("ggg")
f.close()
#result : my nameggg name 

but this will make overwrite on file

f=open("text.txt",mode="r ",encoding="utf-8")

f.seek(7) # set poistion at 7
R = f.read() # "  is name"
f.truncate() # delate all letters after pointer 
#========================
f.seek(0) 
print(f.read()) #result: my name
#========================
f.seek(7) 
# we should reset pointer
f.write("ggg" R)
print(f.read())
f.close()
# text.text contain: my nameggg is name
  • Related