file handling in Python

How to create, read, update and delete files in Python?

0 / 0 2 Mins Admin

December 25, 2022

10 Comments

File Handling in Python: You can use the following functions to create, read, update, and delete files:

  • open(): Opens a file for reading or writing.
  • close(): Closes an open file.
  • write(): Writes data to an open file.
  • read(): Reads data from an open file.
  • os.remove(): Deletes a file.
  • os.path.exists(): Checks if a file exists.
  • os.access(): Checks if a file is readable or writable.

Here is an example of how you can use these functions to handle (CRUD) a file in Python:

import os

#1 Create a file
with open('myfile.txt', 'w') as f:
    f.write('Hello, world!')

#2 Read a file
with open('myfile.txt', 'r') as f:
    contents = f.read()
    print(contents)

#3 Update a file
with open('myfile.txt', 'w') as f:
    f.write('Hello, world! How are you today?')

#4 Delete a file
os.remove('myfile.txt')

#5 Check if a file exists
if os.path.exists('myfile.txt'):
    print("The file exists.")
else:
    print("The file does not exist.")

#6 Check if a file is readable
if os.access('myfile.txt', os.R_OK):
    print("The file is readable.")
else:
    print("The file is not readable.")

#7 Check if a file is writable
if os.access('myfile.txt', os.W_OK):
    print("The file is writable.")
else:
    print("The file is not writable.")

How do the above code snippets work?

  1. This code will create a file called myfile.txt.
  2. Write the text “Hello, world!” to it.
  3. Read the contents of the file and print it on the screen.
  4. Update the contents of the file to “Hello, world! How are you today?”
  5. Delete the file.
  6. Check if the file exists.
  7. Check if the file is readable and writable.