How to create, read, update and delete files in Python?
0 / 0
2 Mins
Admin
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?
- This code will create a file called
myfile.txt
. - Write the text “Hello, world!” to it.
- Read the contents of the file and print it on the screen.
- Update the contents of the file to “Hello, world! How are you today?”
- Delete the file.
- Check if the file exists.
- Check if the file is readable and writable.