File Management in Python: Detailed Explanation
File Management in Python: Detailed Explanation
File management in Python allows us to create, open, read, write, rename, delete, and manipulate files and directories.
1. Opening Files
To open a file in Python, use the open()
function.
Syntax:
file = open("filename", mode, encoding)
filename
: Name or path of the file.mode
: Specifies the file operation mode.encoding
: Specifies the encoding format (e.g., UTF-8).
File Modes:
Mode | Description |
---|---|
'r' |
Read mode (default). Opens file for reading only. |
'w' |
Write mode. Creates a new file or overwrites the file. |
'a' |
Append mode. Adds data to the end of the file. |
'x' |
Create mode. Creates a new file; raises an error if the file already exists. |
'b' |
Binary mode (e.g., 'rb' , 'wb' ). Used for binary files. |
't' |
Text mode (default). Opens file in text mode. |
Example: Opening a File
file = open("example.txt", "w") # Open file in write mode
file.write("Hello, World!") # Write to the file
file.close() # Close the file
2. File Attributes
When a file is opened, you can check its attributes:
file.name
: Returns the file name.file.mode
: Returns the mode in which the file was opened.file.closed
: ReturnsTrue
if the file is closed.
Example:
file = open("example.txt", "r")
print("File Name:", file.name)
print("Mode:", file.mode)
print("Is File Closed?", file.closed)
file.close()
print("Is File Closed?", file.closed)
Output:
File Name: example.txt
Mode: r
Is File Closed? False
Is File Closed? True
3. Reading and Writing Files
3.1 read()
Method
Reads the file content.
Example:
file = open("example.txt", "r")
content = file.read() # Reads entire file
print(content)
file.close()
3.2 readline()
and readlines()
readline()
: Reads one line at a time.readlines()
: Reads all lines into a list.
Example:
file = open("example.txt", "r")
line = file.readline() # Reads first line
print("First Line:", line)
all_lines = file.readlines() # Reads all lines
print("All Lines:", all_lines)
file.close()
3.3 write()
Method
Writes data to the file. If the file doesn't exist, it will create one.
Example:
file = open("example.txt", "w")
file.write("Hello, Python!\n")
file.write("This is a new line.\n")
file.close()
3.4 writelines()
Writes a list of strings to the file.
Example:
file = open("example.txt", "w")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file.writelines(lines)
file.close()
4. tell() and seek() Methods
4.1 tell()
Method
The tell()
method returns the current position of the file pointer.
Example:
file = open("example.txt", "r")
print("Pointer Position:", file.tell()) # At the start
content = file.read(5)
print("Pointer Position after reading 5 characters:", file.tell())
file.close()
4.2 seek()
Method
The seek()
method changes the file pointer's position.
Syntax:
file.seek(offset, whence)
offset
: Number of bytes to move.whence
:0
: Start of file (default).1
: Current position.2
: End of file.
Example:
file = open("example.txt", "r")
file.seek(7) # Move pointer to the 7th byte
content = file.read(5)
print("Read from position 7:", content)
file.close()
5. Closing Files
Always close a file after performing operations using file.close()
or with
statement.
Using with
Statement:
The with
statement automatically closes the file after use.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
# File is closed here automatically
6. Renaming and Deleting Files
Use the os
module for file operations like renaming and deleting.
Renaming Files
Syntax:
import os
os.rename("old_name.txt", "new_name.txt")
Deleting Files
Syntax:
import os
os.remove("file_to_delete.txt")
Example:
import os
# Rename file
os.rename("example.txt", "new_example.txt")
# Delete file
os.remove("new_example.txt")
7. Directories in Python
Python's os
module allows us to work with directories (folders).
Creating a Directory
import os
os.mkdir("new_folder") # Creates a new folder
Deleting a Directory
import os
os.rmdir("new_folder") # Removes an empty folder
Getting the Current Working Directory
import os
print("Current Directory:", os.getcwd())
Listing Files and Folders
import os
print("Files and Folders:", os.listdir("."))
8. Summary Table
Operation | Method/Function | Description |
---|---|---|
Open a file | open() |
Opens a file in the specified mode. |
Read file content | read() , readline() , readlines() |
Reads file content. |
Write to a file | write() , writelines() |
Writes data to a file. |
Close a file | close() |
Closes the file after operations. |
Move pointer | seek(offset, whence) |
Moves file pointer to a specified location. |
Check pointer position | tell() |
Returns the current file pointer position. |
Rename a file | os.rename() |
Renames a file. |
Delete a file | os.remove() |
Deletes a file. |
Create a directory | os.mkdir() |
Creates a new directory. |
Delete a directory | os.rmdir() |
Deletes an empty directory. |
List directory content | os.listdir() |
Lists files and folders in a directory. |
Example: Combining File Operations
import os
# Step 1: Create a new file and write to it
with open("sample.txt", "w") as file:
file.write("Hello, this is a test file.\n")
file.write("Python file management is easy.\n")
# Step 2: Read the file content
with open("sample.txt", "r") as file:
print("File Content:")
print(file.read())
# Step 3: Rename the file
os.rename("sample.txt", "test_file.txt")
# Step 4: Delete the file
os.remove("test_file.txt")
print("File operations completed successfully!")
Let me know if you need further clarification or examples! 😊
Comments
Post a Comment