In Python, you can open a file with read, write or append mode using “r”, “w”, or “a” parameters as shown in the below examples –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
with open("test.txt", "w") as myfile: myfile.write("write text\n") myfile.close() with open("test.txt", "r") as myfile: t = myfile.read() print(t) myfile.close() with open("test.txt", "a") as myfile: myfile.write("appended text\n") myfile.close() ## 'w' write text ## 'r' read text ## 'a' append text ## 'r+' read + write text ## 'w+' read + write text ## 'a+' append + read text ## 'rb' read binary ## 'wb' write binary ## 'ab' append binary ## 'rb+' read + write binary ## 'wb+' read + write binary ## 'ab+' append + read binary |