Python file handeling

@Thakur666 June 01, 2026

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File handling allows Python programs to create, read, write, append, and manage files stored on a computer.

syntax

for file handling

  file_object = open("filename", "mode")

modes

| Mode   | Description                         |
| -------------------------------------------- |
| `"r"`  | Read                                |
| `"w"`  | Write                               |
| `"a"`  | Append                              |
| `"x"`  | Create a new file                   |
| `"r+"` | Read and write                      |
| `"w+"` | Write and read                      |
| `"a+"` | Append and read                     |

for example :-

let S_THAKUR.txt is a sample file contain:- HELLO EVERY ONE

1.read("r")

f = open("S_THAKUR.txt", "r")
content = f.read()
print(content)
f.close()

output

HELLO EVERY ONE

2.write("w")

file = open("S.THAKUR.txt","w")

content = file.write("thank you")
print(content)

file.close()

output:-

9

note:- this ("w") mode remove previous content from the file and save new one.

3.append("a")

file = open("S.THAKUR.txt","a")

content = file.write("\nthe one piece is real")
print(content)

file.close()

output:-

HELLO EVERY ONE
the one piece is real

note:- here ("a") mode add the new content with previous content.

4.creat a new file("x")

file = open("S.THAKUR.txt", "x")

file.write("New File Created")

file.close()

output:-

FileExistsError

note:-Creates a new file or Gives an error if the file already exists.

***5.read and write("r+")

file = open("S.THAKUR.txt", "r+")

print(file.read())

file.write("\n welcome")

file.close()

output:-

HELLO EVERY ONE
the one piece is real

note:-print the previous content and write the new content

6.write and read("w+")

file = open("S.THAKUR.txt", "w+")

file.write("Python Programming")

file.seek(0)

print(file.read())

file.close()

output:-

Python Programming

note:-Creates a file if needed and clears existing content.

7.append and read("a+")

file = open("S.THAKUR.txt", "a+")

file.write("\nthe boss")

file.seek(0)

print(file.read())

file.close()

output:-

HELLO EVERY ONE
the one piece is real
the boss

note:-Appends data and also allows reading.

0 Likes
68 Views

Filters

No filters available for this view.

Reset All