In this article we want to learn about Python File Management, Python is high level programming language, and also it has the power for file management tasks. because Python has a lot of powerful libraries that make it easy to perform different operations on file management, it has the ability for operations like reading, writing and manipulating files, in this article we want to talk about different file management techniques and libraries in Python.
Opening and Closing Files
Before you can perform any file operations, you need to open the file. Python builtin open() function is used to open files.
This is the basic syntax.
1 |
file_object = open("filename", "mode") |
After that you are done with performing file operations, it is important to close the file to release the resources. you can use close() function to close the file like this:
1 |
file_object.close() |
Reading Files
Python provides several methods to read files, it depends on the type of file and required output. most commonly used method is the readline() function that reads a single line from the file at a time.
This code reads a file line by line:
1 2 3 4 |
file_object = open("filename", "r") for line in file_object: print(line) file_object.close() |
Also you can use read() function to read the entire file content as a string.
1 2 3 4 |
file_object = open("filename", "r") content = file_object.read() print(content) file_object.close() |
Writing Files
For writing to Python file, you can use write() function like this.
1 2 3 |
file_object = open("filename", "w") file_object.write("Welcome to geekscoders.com") file_object.close() |
Appending Files
If you want to append content to an existing file without deleting the existing content, you can use append mode a. this code appends a line to an existing file.
1 2 3 |
file_object = open("filename", "a") file_object.write("This line is appended!") file_object.close() |
Deleting Files
For deleting a file using Python, you can use remove() function from the os module.
1 2 |
import os os.remove("filename") |